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]:
Enumeration type comprises both those types that are declared with
enumand those that are declared withenum classorenum 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
intas their underlying types their range of values is the same as that ofint: fromINT_MINtoINT_MAX(inclusive).Since
42has typeintand is obviously a value ofintthe behaviour is defined.