How to define strong ID types in C ++ 11?

How to define strong ID types in C ++ 11? Is it possible to execute an alias of integer types, but receive warnings from the compiler when mixing types?

eg:

using monsterID = int; using weaponID = int; auto dragon = monsterID{1}; auto sword = weaponID{1}; dragon = sword; // I want a compiler warning here!! if( dragon == sword ){ // also I want a compiler warning here!! // you should not mix weapons with monsters!!! } 
+6
source share
1 answer

If you are using boost, try BOOST_STRONG_TYPEDEF

Example from the documentation:

 BOOST_STRONG_TYPEDEF(int, a) void f(int x); // (1) function to handle simple integers void f(ax); // (2) special function to handle integers of type a int main(){ int x = 1; ay; y = x; // other operations permitted as a is converted as necessary f(x); // chooses (1) f(y); // chooses (2) } 
+5
source

Source: https://habr.com/ru/post/952117/


All Articles