枚举类是否可以转换为底层类型? [英] Can an enum class be converted to the underlying type?
问题描述
有没有办法将枚举类
字段转换为底层类型?我认为这是自动的,但显然不是。
Is there a way to convert an enum class
field to the underlying type? I thought this would be automatic, but apparently not.
enum class my_fields : unsigned { field = 1 };
unsigned a = my_fields::field;
该作业被GCC拒绝。 错误:无法在赋值
中将'my_fields'转换为'unsigned int'。
That assignment is being rejected by GCC. error: cannot convert 'my_fields' to 'unsigned int' in assignment
.
推荐答案
我认为您可以使用 std :: underlying_type 了解底层类型,然后使用cast :
I think you can use std::underlying_type to know the underlying type, and then use cast:
#include <type_traits> //for std::underlying_type
typedef std::underlying_type<my_fields>::type utype;
utype a = static_cast<utype>(my_fields::field);
这样,您不必或者你不必在枚举类
的定义中提及它 enum class my_fields:int {....} $
With this, you don't have to assume the underlying type, or you don't have to mention it in the definition of the enum class
like enum class my_fields : int { .... }
or so.
您甚至可以编写一个泛型转换函数,该函数应该能够转换任何 > 枚举类
到其底层的整数类型:
You can even write a generic convert function that should be able to convert any enum class
to its underlying integral type:
template<typename E>
constexpr auto to_integral(E e) -> typename std::underlying_type<E>::type
{
return static_cast<typename std::underlying_type<E>::type>(e);
}
然后使用它:
auto value = to_integral(my_fields::field);
auto redValue = to_integral(Color::Red);//where Color is an enum class!
由于函数声明为 constexpr
,您可以在需要常量表达式的地方使用它:
And since the function is declared to be constexpr
, you can use it where constant expression is required:
int a[to_integral(my_fields::field)]; //declaring an array
std::array<int, to_integral(my_fields::field)> b; //better!
希望有帮助。
这篇关于枚举类是否可以转换为底层类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!