关于c ++:如何在C ++ 11中定义强ID类型?

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

本问题已经有最佳答案,请猛点这里访问。

如何在C ++ 11中定义强ID类型? 可以对整数类型进行别名处理,但是在混合类型时会收到来自编译器的警告?

例如:

1
2
3
4
5
6
7
8
9
10
11
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!!!
}


如果您使用Boost,请尝试BOOST_STRONG_TYPEDEF

文档中的示例:

1
2
3
4
5
6
7
8
9
10
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)
}