I'm writing code where I'm creating multiple aliases for primitive types, e.g. Address and Id being ints.
I want to avoid using Addresses and Ids together, e.g. in arithmetic operations.
Thus I would like to have type-checking on these aliases, so that the following result can be obtained:
typedef int A;
typedef int B;
A f(A a) { return a+a; };
int main()
{
A a = 5;
B b = 5;
f(a); // I would like this to work...
f(b); // and this not to compile.
}
Now this does not work, but I know I can use a wrapper struct/class with just one member:
class A { public: int x; A(int xx) { x = xx; }};
class B { public: int x; B(int xx) { x = xx; }};
A f(A a) { return A(a.x+a.x); }; // this is ugly and I'd want to be able to use: return a+a
int main()
{
A a = 5;
B b = 5;
f(a); // This will work...
f(b); // This won't compile...
}
My question is - what's the best way I can get code working like the 2nd snippet, but without having to explicitly getting x all the time and construct new objects (as noted in the line with the "this is ugly" comment)?
I guess I can overload all relevant operators for all my 'aliases' but that's a lot of work and I'm hoping there's a faster/nicer solution.
Thanks.
PS To make this a concrete SO question, not a discussion: I'm just asking for a different way of achieving the result I want, than overloading everything. Thank you.