如何在C ++ 11中输出枚举类的值 [英] How can I output the value of an enum class in C++11

查看:413
本文介绍了如何在C ++ 11中输出枚举类的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在C ++ 11中输出枚举类的值?在C ++ 03中,它是这样:

  #include< iostream> 

using namespace std;

枚举A {
a = 1,
b = 69,
c = 666
};

int main(){
A a = A :: c;
cout<< a<< endl;
}

在c ++ 0x中此代码不编译

  #include< iostream> 

using namespace std;

枚举类A {
a = 1,
b = 69,
c = 666
};

int main(){
A a = A :: c;
cout<< a<< endl;
}


prog.cpp:13:11:错误:无法将'std :: ostream'lvalue绑定到'std :: basic_ostream< char>&
/usr/lib/gcc/i686-pc-linux-gnu/4.5.1/../../../../include/c++/4.5.1/ostream:579:5:错误:初始化'std :: basic_ostream< _CharT,_Traits>& std :: operator<<<<<<(std :: basic_ostream< _CharT,_Traits&&&&& amp; const _Tp&在Ideone.com中编译的


/ div>

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

  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; 


How can I output the value of an enum class in C++11? In C++03 it's like this:

#include <iostream>

using namespace std;

enum A {
  a = 1,
  b = 69,
  c= 666
};

int main () {
  A a = A::c;
  cout << a << endl;
}

in c++0x this code doesn't compile

#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]'

compiled at Ideone.com

解决方案

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;

这篇关于如何在C ++ 11中输出枚举类的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆