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
?
Strongly-typed enumerationsThe enumerators can only be accessed in the scope of the enumeration. The enumerators don't implicitly convert to int. The enumerators aren't imported in the enclosing scope. The type of the enumerators is by default int. Therefore, you can forward the enumeration.
Enum, which is also known as enumeration, is a user-defined data type that enables you to create a new data type that has a fixed range of possible values, and the variable can select one value from the set of values.
You can use an enumerated value just like an integer: myChoice c; ... switch( c ) { case EASY: DoStuff(); break; case MEDIUM: ... }
An enumeration type is still an enumeration type even whether strongly typed or not, and have always worked fine in switch
statements.
See this program for example:
#include <iostream> enum class E { A, B }; int main() { E e = E::A; switch (e) { case E::A: std::cout << "A\n"; break; case E::B: std::cout << "B\n"; break; } }
The output of this is "A".
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