Consider the following:
#include <iostream>
enum class E : bool { A, B };
void foo(E e)
{
switch(e)
{
case E::A: break;
case E::B: break;
default: std::cout << "aha
";
}
}
int main()
{
foo( static_cast<E>(3) );
}
My question is: Can the default
case be triggered, i.e. this program generates output?
The tricky point in N3936 seems to be the specification of static_cast
when converting an out-of-range integer to enumeration type, [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. Otherwise, the resulting
value is unspecified (and might not be in that range).
The bolded text does not explicitly say that the value must still be within the range of the underlying type, but I am wondering if it were intended that it did.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…