// Old C++ Enum enum OldSchoolEnum { ValA = 0, ValB = 100, ValC = 10000, };
// C++ 11 Enum Class enumclassModernEnum :short// We can explicit specify the underlying type { ValA = 0, ValB = 100, ValC = 10000, };
intmain(){ //Usage of OldSchoolEnum OldSchoolEnum myEnum1 = ValB; //ValB is in global namespace. Bad! int myInt = myEnum1; //Can implicit cast to int. Bad! //myEnum1 = myInt; //ERROR! Can't implicit cast int to enum myEnum1 = static_cast<OldSchoolEnum>(myInt); //We can do it by explicit cast std::cout << myEnum1 << std::endl; //Print 100
//Usage of ModernEnum ModernEnum myEnum2 = ModernEnum::ValB; //ValB is in class namespace. Good! //myInt = myEnum2; //ERROR! Can't implicit cast myEnum2 to int myInt = static_cast<int>(myEnum2); //We can do it by explicit cast //myEnum2 = myInt; //Also ERROR! myEnum2 = static_cast<ModernEnum>(myInt); //Also success by explicit cast //std::cout << myEnum2 << std::endl; //ERROR! Can't implicit myEnum2 to any numerical type using ModernEnum_underlying_t = std::underlying_type<ModernEnum>::type; //First, we get the underlying type of ModernEnum std::cout << static_cast<ModernEnum_underlying_t>(myEnum2) << std::endl;//Second, We implement cout by cast to underlying type
return0; }
上面的代码涵盖了大部分的注意点,直接看注释即可。
前向声明
除此之外,enum class还支持前向声明,以便于减少依赖,减少编译时间。可以参考以下代码:
Orientation.h
1 2 3 4 5 6 7 8 9 10
#pragma once enumclassOrientation { FRONT = 1, BACK = 2, LEFT = 3, RIGHT = 4, TOP = 5, DOWN = 6 };
BoxFace.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#pragma once //Don't need to #include "Orientation.h" //Forward declaration of enum class enumclassOrientation;