Why does the following switch even compiles the default case since it covers all items of the enum class?
I would have thought that this was the reason for having strong enum class
in the first place.
As to why I would like to have a default even though I know that I cover all cases : This safe-guards me against my future careless-ness (and that of other coworkers)
enum class E {
a,
b
};
int main()
{
E c = E::b;
switch (c) {
case E::a:
case E::b:
std::cout << "pass" << std::endl;
break;
default:
static_assert(false, "This explodes!");
}
}
Proof
Because the compile can't know if someone casted an illegal value to the enum type. Consider:
E c = static_cast<E>( 42 );
The cast will compile without a warning (or even an error) as you are explicitly telling the compiler "I know what I'm doing, don't check the value". In practice, this sadly happens more often than you think. :(
Also, all code needs to be valid, even if it is later removed as unreachable. A static_assert(false,...)
will fire at compile-time, independent of what would happen at run-time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With