将基础类型的任意值转换为强类型枚举类型是否安全?
如果我有一个强类型枚举,例如基础类型 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);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从 n3290,5.2.9 静态转换 [expr.static.cast]:
枚举类型包括使用
enum
声明的类型和使用enum class
或enum声明的类型struct
,标准分别将其称为无范围枚举和范围枚举。 7.2 枚举声明 [dcl.enum] 中有更详细的描述。枚举类型的值不会与其枚举器相混淆。在您的情况下,由于您声明的枚举都将
int
作为其基础类型,因此它们的值范围与int
相同:来自INT_MIN
到INT_MAX
(含)。由于
42
具有int
类型,并且显然是int
的值,因此定义了行为。From n3290, 5.2.9 Static cast [expr.static.cast]:
Enumeration type comprises both those types that are declared with
enum
and those that are declared withenum class
orenum struct
, which the Standard calls respectively unscoped enumerations and scoped enumerations. Described in more details in 7.2 Enumeration declarations [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 ofint
: fromINT_MIN
toINT_MAX
(inclusive).Since
42
has typeint
and is obviously a value ofint
the behaviour is defined.