简体   繁体   English

将基础类型的任意值强制转换为强类型枚举类型是否安全?

[英]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 classenum 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_MININT_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.

相关问题 为什么C ++ 11强类型枚举不能通过指针强制转换为底层类型? - Why can't C++11 strongly-typed enum be cast to underlying type via pointer? 将指向typed / size enum的指针转换为指向底层类型的指针是否安全? - Is it safe to convert a pointer to typed/sized enum to a pointer to the underlying type? 将枚举类变量重新解释为基础类型的引用是否安全? - Is it safe to reinterpret_cast an enum class variable to a reference of the underlying type? 为什么强类型枚举可以用没有static_cast的整数初始化? - Why can a strongly-typed enum be initialized with an integer without static_cast? 强类型枚举不允许用作相同底层类型的参数? - strongly typed enums not allowed to be used as arguments of the same underlying type? 在编译时将强类型的枚举器转换为其基础类型? - convert strongly typed enumerator to its underlying type in compilation time? C ++ 11中弱类型枚举的基础类型 - Underlying type of weak typed enum in C++11 枚举 class 的 C 风格转换为基础类型 char 的引用 - C-style cast of enum class to reference of underlying type char 枚举 class 具有范围但不必强制转换为基础类型 - enum class with scoping but without having to cast to underlying type 底层类型的无范围枚举? - Underlying type of an unscoped enum?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM