Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch Statements with strongly typed enumerations

Tags:

c++

enums

c++11

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?

like image 951
mark Avatar asked Jan 30 '12 09:01

mark


People also ask

What is a strongly typed enum?

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.

What are enumerations used for in C++?

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.

Can enum be used in switch case in C++?

You can use an enumerated value just like an integer: myChoice c; ... switch( c ) { case EASY: DoStuff(); break; case MEDIUM: ... }


1 Answers

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".

like image 102
Some programmer dude Avatar answered Sep 28 '22 17:09

Some programmer dude