如何在 C++11 中输出 enum class
的值?在 C++03 中是这样的:
#include <iostream>
using namespace std;
enum A {
a = 1,
b = 69,
c= 666
};
int main () {
A a = A::c;
cout << a << endl;
}
在 c++0x 中,此代码无法编译
#include <iostream>
using namespace std;
enum class A {
a = 1,
b = 69,
c= 666
};
int main () {
A a = A::c;
cout << a << endl;
}
prog.cpp:13:11: error: cannot bind 'std::ostream' lvalue to 'std::basic_ostream<char>&&'
/usr/lib/gcc/i686-pc-linux-gnu/4.5.1/../../../../include/c++/4.5.1/ostream:579:5: error: initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char, _Traits = std::char_traits<char>, _Tp = A]'
编译于 Ideone.com
最佳答案
与非范围枚举不同,范围枚举不能隐式转换为其整数值。您需要显式使用强制转换将其转换为整数:
std::cout << static_cast<std::underlying_type<A>::type>(a) << std::endl;
您可能希望将逻辑封装到函数模板中:
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);
}
用作:
std::cout << as_integer(a) << std::endl;
关于c++ - 如何在 C++11 中输出枚举类的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11421432/