C++11中如何输出enumclass的值
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
3namespace myenum {
4// ⼀般的枚举
5enum PieceType {
6    PieceTypeKing, PieceTypeQueen, PieceTypeRook, PieceTypePawn
7  };
8
9// 设置了值得枚举
10enum PieceTypeAnother {
11    PieceTypeKingA=1, PieceTypeQueenA, PieceTypeRookA=10, PieceTypePawnA
12  };
13// 强类型的枚举
14enum class MyEnum {
15    EnumValue1,
16      EnumValue2 = 10,
17      EnumValue3
18      };
19// 改变了类型的强类型枚举
20enum 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) { 27return stream << static_cast<typename std::underlying_type<T>::type>(e);
28  }
29 }
main函数:main.cpp
1 #include "enum.h"
enum函数
2int 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

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。