杂货边角(26):强枚举类型enum class

枚举类型是C++从C继承而来的特性,可是枚举类型在C中的实现其实和宏无差异,即java

#define Male 0
#define Female 1
....
//用枚举声明为
enum {Male, Female}

这种枚举类型和int整数的自然等价性很容易形成一些漏洞,如不一样枚举名字域下的比较,而且传统的枚举类型中的符号是直接开发在父做用域中,这也容易致使符号冲突。而C++11引入的强枚举类型,很是好理解,而且安全性也更强。ios

#include <iostream>

using namespace std;

enum class Type : int { General, Light, Medium, Heavy }; //表明用int字节来表示每一个符号
enum class Category : char { General = 1, Pistol, MachineGun, Cannon }; //表明用char即1个字节来实现各符号,能够节省空间

int main()
{
    Type t = Type::Light;
    //t = General; //强做用域限制,必需要携带枚举class::限定,不像传统的枚举类型能够直接穿透到父做用域
    //制止了enum符号成员直接输出到父做用域,避免名字空间间符号冲突的问题
    /******** if (t == Category::General ) //不一样枚举类之间不能比较,传统的枚举类型是宏的syntax sugar,在程序中都表示为整数 //故而能够默认比较,可是这种跨不一样enum间的比较,容易出现混淆 //error: no match for 'operator==' (operand types are 'Type' and 'Category') cout << "General Weapon" << endl; *********/
    if (t > Type::General)
        cout << "Not General Weapon" << endl;

    /******** if (t > 0) //强枚举类型并不能调用隐式的static_cast<int>转换为整型,须要显式调用才可 //error: no match for 'operator>' (operand types are 'Type' and 'int') cout << "Not General Weapon" << endl; *********/

    cout << sizeof(Type::General) << endl; //4
    cout << sizeof(Category::General) << endl; //1

    if ((int)t > 0)
        cout << "Not General Weapon" << endl;

    cout << is_pod<Type>::value << endl;
    cout << is_pod<Category>::value << endl;

    return 0;
}