An extension to the answers from R. Martinho Fernandes and Class Skeleton: Their answers show how to use typename std::underlying_type<EnumType>::type or std::underlying_type_t<EnumType> to convert your enumeration value with a static_cast to a value of the underlying type. Compared to a static_cast to some specific integer type, like, static_cast<int> this has the benefit of being maintenance friendly, because when the underlying type changes, the code using std::underlying_type_t will automatically use the new type.
然而,这有时不是你想要的:假设你想直接打印出枚举值,例如std::cout,如下例所示:
enum class EnumType : int { Green, Blue, Yellow };
std::cout << static_cast<std::underlying_type_t<EnumType>>(EnumType::Green);
如果你稍后将底层类型更改为字符类型,例如uint8_t,那么EnumType::Green的值将不会作为数字打印,而是作为字符打印,这很可能不是你想要的。因此,您有时更愿意将枚举值转换为类似于“底层类型,但在必要时使用整数提升”的类型。
如果需要,可以对强制转换的结果应用一元运算符+来强制提升整数。然而,你也可以使用std::common_type_t(同样来自头文件<type_traits>)来做以下事情:
enum class EnumType : int { Green, Blue, Yellow };
std::cout << static_cast<std::common_type_t<int, std::underlying_type_t<EnumType>>>(EnumType::Green);
最好将这个表达式包装在某个helper模板函数中:
template <class E>
constexpr std::common_type_t<int, std::underlying_type_t<E>>
enumToInteger(E e) {
return static_cast<std::common_type_t<int, std::underlying_type_t<E>>>(e);
}
这样看起来更友好,对底层类型的更改维护更友好,并且不需要使用operator+的技巧:
std::cout << enumToInteger(EnumType::Green);