Is there a solution to force a type in case the type itself is an alias?
Example:
using my_type = uint32_t;
void my_function(my_type type) { ... }
In the example above, valid code is both A and B:
A: proper implementation
int main()
{
my_type type = 0;
my_function(type);
return 0;
}
B: valid but improper implementation
int main()
{
uint32_t type = 0; // <--- true type instead of alias
my_function(type);
return 0;
}
is there a way i could force a compiler error (GCC) if the true-type is used instead of the alias? in the example of enums, in C++ i typically "force" it by using "enum class" rather than "enum".
im looking for a similar solution.
Note:
Of course in this case it's questionable if this even makes sense. I used a super simplified code example above to demonstrate my question. In my actual use case its important to have such a solution.
No, there isn't anything simple for this in the language.
The usual approach is to define my_type
as a class type with uint32_t
as only member and overloading the operators so that my_type
behaves like a uint32_t
(potentially with restrictions).
This concept is called "strong types" and it probably makes sense to use a library that implements them generically as templates.