#include <iostream>
typedef uint32_t type1;
struct type2
{
type2(uint32_t i) : i(i) {}
inline operator uint32_t() { return i; }
private:
uint32_t i;
};
void x(uint32_t num) {
std::cout << "uint32_t: ";
std::cout << (num << 30) << std::endl;
}
// redefinition of x
// void x(type1 num) {
// std::cout << "type1: ";
// std::cout << (num << 30) << std::endl;
// }
void x(type2 num) {
std::cout << "type2: ";
std::cout << (num << 30) << std::endl;
}
int main()
{
uint32_t num = 15;
type1 num1 = 15;
type2 num2 = 15;
x(num);
x(num1);
x(num2);
}
Here, I want to create another type that is equivalent to uint32_t
. if I use typedef
, I'll just create an alias, and I won't be able to overload functions using it.
creating a struct and adding a cast operator is one way of doing it, but it's a bit of a boilerplate.
I'm not even sure whether this is optimal or not. Should I make the cast operator inline
as in this code, so that no function is being called for casting? Or should I assume that the compiler is smart enough to optimize this and treat it just as a uint32_t
?
Is there a better way of doing this?
Update: I meant a user-defined type that behaves like a primitive data type of choice. This way, I get the speed and the already defined operators and functions for that type for free.