将底层类型的任意值转换为强类型枚举类型是安全的吗? [英] Is it safe to cast arbitrary values of the underlying type to a strongly-typed enum type?

查看:73
本文介绍了将底层类型的任意值转换为强类型枚举类型是安全的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个强类型的枚举,说,底层类型 int ,可以铸造 int

If I have a strongly-typed enum, with say, underlying type int, is it ok to cast an int value that does not match any enumerator to the enum type?

enum e1 : int { x = 0, y = 1 };
enum class e2 : int { x = 0, y = 1 };

int main() {
        e1 foo = static_cast<e1>(42); // is this UB?
        e2 bar = static_cast<e2>(42);
}


推荐答案

静态转型[expr.static.cast]:

From n3290, 5.2.9 Static cast [expr.static.cast]:


10整数或枚举类型的值可以将
显式转换为枚举类型。如果原始值
在枚举值(7.2)的范围内,则值不变。否则,
结果值未指定(可能不在该范围内)。 [...]

10 A value of integral or enumeration type can be explicitly converted to an enumeration type. The value is unchanged if the original value is within the range of the enumeration values (7.2). Otherwise, the resulting value is unspecified (and might not be in that range). [...]

枚举类型包括 enum 和那些用枚举类 enum struct 声明的标准分别调用无范围枚举和范围枚举。 7.2枚举声明[dcl.enum]中更详细地描述。

Enumeration type comprises both those types that are declared with enum and those that are declared with enum class or enum struct, which the Standard calls respectively unscoped enumerations and scoped enumerations. Described in more details in 7.2 Enumeration declarations [dcl.enum].

枚举类型的不会与其 >枚举。在你的情况下,因为你声明的枚举都有 int 作为它们的底层类型,它们的值范围与 int :从 INT_MIN INT_MAX (含)。

The values of an enumeration type are not be confused with its enumerators. In your case, since the enumerations you declared all have int as their underlying types their range of values is the same as that of int: from INT_MIN to INT_MAX (inclusive).

由于 42 有类型 int ,显然是 int 定义行为。

Since 42 has type int and is obviously a value of int the behaviour is defined.

这篇关于将底层类型的任意值转换为强类型枚举类型是安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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