c++11 - How to create nice-to-use type-checked aliases for primitive types in C++? -


this question has answer here:

i'm writing code i'm creating multiple aliases primitive types, e.g. address , id being ints.

i want avoid using addresses , ids together, e.g. in arithmetic operations.

thus have type-checking on these aliases, following result can obtained:

typedef int a; typedef int b;  f(a a) { return a+a; };  int main() {   a = 5;   b b = 5;   f(a);     // work...   f(b);     // , not compile. } 

now not work, know can use wrapper struct/class 1 member:

class { public: int x; a(int xx) { x = xx; }}; class b { public: int x; b(int xx) { x = xx; }};  f(a a) { return a(a.x+a.x); }; // ugly , i'd want able use: return a+a  int main() {   a = 5;   b b = 5;   f(a);     // work...   f(b);     // won't compile... } 

my question is - what's best way can code working 2nd snippet, without having explicitly getting x time , construct new objects (as noted in line "this ugly" comment)?

i guess can overload relevant operators 'aliases' that's lot of work , i'm hoping there's faster/nicer solution.

thanks.

ps make concrete question, not discussion: i'm asking different way of achieving result want, overloading everything. thank you.

i don't know "best" way 1 thing can create one type overloads relevant operators , takes integral template parameter can differentiate types number:

template<std::size_t id> class strongly_typed_int { public:     explicit strongly_typed_int(int = 0): i(i) {}      // ...      strongly_typed_int operator+(strongly_typed_int i) { /*...*/ }     // etc...  private:     int i; };  using security_id = strongly_typed_int<0>; using access_code = strongly_typed_int<1>; // etc... 

Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -