[英]Is it safe to cast arbitrary values of the underlying type to a strongly-typed enum type?
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? 如果我有一个强类型的枚举,比如底层类型
int
,是否可以将一个与枚举类型不匹配的int
值转换为枚举类型?
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);
}
From n3290, 5.2.9 Static cast [expr.static.cast]: 来自n3290,5.2.9 Static cast [expr.static.cast]:
10 A value of integral or enumeration type can be explicitly converted to an enumeration type.
10可以将整数或枚举类型的值显式转换为枚举类型。 The value is unchanged if the original value is within the range of the enumeration values (7.2).
如果原始值在枚举值(7.2)的范围内,则该值不变。 Otherwise, the resulting value is unspecified (and might not be in that range).
否则,结果值未指定(可能不在该范围内)。 [...]
[...]
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. 枚举类型包括使用
enum
声明的那些类型和使用enum class
或enum struct
声明的类型,标准分别调用未编组的枚举和作用域枚举。 Described in more details in 7.2 Enumeration declarations [dcl.enum]. 在7.2枚举声明[dcl.enum]中有更详细的描述。
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). 在你的情况下,由于枚举你宣布都有
int
作为它们的基础类型的值的范围是相同的int
:从INT_MIN
到INT_MAX
(含)。
Since 42
has type int
and is obviously a value of int
the behaviour is defined. 由于
42
具有int
类型,并且显然是int
的值,因此定义了行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.