c++ - 如何在 C++11 中输出枚举类的值

标签 c++ c++11 templates enums enum-class

如何在 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/

相关文章:

c++ - 将依赖的模板类加为好友

嵌入式软件编程中的C++

c++ - 以方便的方式在 C++ 中使用方法作为回调

C++11 资源和编译器

c++ - 如何对可变参数函数中的所有参数调用 std::forward ?

php - 带有命名参数的 vsprintf 或 sprintf,或者 PHP 中的简单模板解析

c++ - 虚函数和性能 C++

c++ - “可变”变量只能通过一种 const 方法可变吗?

c++ - 如果您必须检查溢出或有条件地采取行动, std::atomic 是否多余?

c++ - 以派生类作为参数的专用模板方法