雑貨コーナー(26):強列挙タイプenum class

2694 ワード

列挙タイプはC++がCから継承した特性であるが、列挙タイプのCでの実装はマクロと差がない.
#define Male 0
#define Female 1
....
//      
enum {Male, Female}

このような列挙タイプとint整数の天然等価性は、異なる列挙名ドメインでの比較のような脆弱性をもたらしやすく、従来の列挙タイプのシンボルは親役割ドメインに直接開発されており、シンボル競合を招きやすい.一方,C++11が導入した強い列挙タイプは,非常によく理解され,セキュリティもより強い.
#include 

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     ,        
        //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::value << endl;
    cout << is_pod::value << endl;

    return 0;
}