6

How to define strong ID types in C++11? It's posible to done alias of integer types but getting warnings from compiler when you mix types?

E.g:

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!!!
}
R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
Zhen
  • 4,171
  • 5
  • 38
  • 57

1 Answers1

5

If youre 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(a x);    // (2) special function to handle integers of type a 
int main(){
    int x = 1;
    a y;
    y = x;      // other operations permitted as a is converted as necessary
    f(x);       // chooses (1)
    f(y);       // chooses (2)
}
Viktor Sehr
  • 12,825
  • 5
  • 58
  • 90
  • Thanks. I think it's a great solution. But I was looking if with new standard C++11 it's posible to do it without using macros, or fully classes. – Zhen Aug 20 '13 at 16:14