简体   繁体   中英

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?

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]:

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). [...]

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].

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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM