Unlike an unscoped enumeration, a scoped enumeration is not implicitly convertible to its integer value. You need to explicitly convert it to an integer using a cast:
std::cout << static_cast<std::underlying_type<A>::type>(a) << std::endl;
You may want to encapsulate the logic into a function template:
template <typename Enumeration>
auto as_integer(Enumeration const value)
-> typename std::underlying_type<Enumeration>::type
{
return static_cast<typename std::underlying_type<Enumeration>::type>(value);
}
used as:
std::cout << as_integer(a) << std::endl;
示例:
头文件:enum.h
1 #include <iostream> 2 3 namespace myenum { 4 // 一般的枚举 5 enum PieceType { 6 PieceTypeKing, PieceTypeQueen, PieceTypeRook, PieceTypePawn 7 }; 8 9 // 设置了值得枚举 10 enum PieceTypeAnother { 11 PieceTypeKingA=1, PieceTypeQueenA, PieceTypeRookA=10, PieceTypePawnA 12 }; 13 // 强类型的枚举 14 enum class MyEnum { 15 EnumValue1, 16 EnumValue2 = 10, 17 EnumValue3 18 }; 19 // 改变了类型的强类型枚举 20 enum class MyEnumLong : unsigned long { 21 EnumValueLong1, 22 EnumValueLong2 = 10, 23 EnumValueLong3 24 }; 25 26 template<typename T> std::ostream& operator<<(typename std::enable_if<std::is_enum<T>::value, std::ostream>::type& stream, const T& e) { 27 return stream << static_cast<typename std::underlying_type<T>::type>(e); 28 } 29 }
main函数:main.cpp
1 #include "enum.h" 2 int main() { 3 4 std::cout << "test enum" << std::endl; 5 std::cout << "一般的枚举" << myenum::PieceType::PieceTypeKing << std::endl; 6 std::cout << "设置了值的枚举" << myenum::PieceTypeAnother::PieceTypeQueenA << std::endl; 7 std::cout << "强类型的枚举" << myenum::MyEnum::EnumValue3 << std::endl; 8 std::cout << "改变了类型的强类型枚举" << myenum::MyEnumLong::EnumValueLong1 << std::endl; 9 10 std::cout << "end of this program" << std::endl; 11 }
重写了之后,就不用再对强类型的进行强转了,呵呵
编译的时候要加上c++11的选项:
1 g++ main.cpp -std=c++11