如何在C ++ 11中定义强ID类型?

时间:2013-08-20 14:52:17

标签: c++ c++11 types

如何在C ++ 11中定义强ID类型?可以使用整数类型的别名,但在混合类型时会从编译器收到警告吗?

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!!!
}

1 个答案:

答案 0 :(得分:5)

如果您正在使用提升,请尝试BOOST_STRONG_TYPEDEF

文档中的示例:

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)
}