When using strongly typed enums in a switch statement is there a way to avoid explicit casts to int?
/// @desc an enumeration of the states that the session can be in.
enum class State
{
Created,
Connected,
Active,
Closed
};
State sesState = session->GetState();
switch (static_cast<int>(sesState))
{
case static_cast<int>(Session::State::Created):
// do stuff.
break;
case static_cast<int>(Session::State::Connected):
// do stuff.
break;
}
From the n3242 draft:
6.4.2 The switch statement [stmt.switch]
2 The condition shall be of integral type, enumeration type, or of a class type for which a single non-explicit conversion function to integral or enumeration type exists (12.3).
Does enumeration type include strongly typed enums or are they incompatible with switch statements because they require an explicit conversion to int?
An enumeration type is still an enumeration type even whether strongly typed or not, and have always worked fine in
switchstatements.See this program for example:
The output of this is “A”.