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

新手上路,请多包涵

如何在 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 编译

原文由 Adi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 871
2 个回答

与无范围枚举不同,有范围枚举不能 隐式 转换为其整数值。您需要使用强制转换将其 显式 转换为整数:

 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;

原文由 James McNellis 发布,翻译遵循 CC BY-SA 3.0 许可协议

扩展 James McNellis 的出色回答,如果您的编译器支持 概念和约束(在 C++20 中引入),它可用于引入额外的编译时健全性(如更清晰地指示任何不正确的用法)以以以下简单明了的方式创建函数模板:

 template<typename E>
concept EnumType = std::is_enum_v<E>;

template <EnumType E>
constexpr std::underlying_type_t<E> enumUnderlyingType(E const underlying_type)
{
    return static_cast<std::underlying_type_t<E>>(underlying_type);
}

原文由 axton 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题