Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching on scoped enum

I am trying to switch on a scoped-enum with the type unsigned int:

The enum is defined as:

const enum struct EnumType : unsigned int { SOME = 1, MORE = 6, HERE = 8 };

I receive a const unsigned int reference and I am trying to check that value against the enum values.

void func(const unsigned int & num)
{
    switch (num)
    {
    case EnumType::SOME:
        ....
        break;
    case EnumType::MORE:
        ....
        break;

    ....

    default:
        ....
    }
}

This results in a syntax error: Error: This constant expression has type "EnumType" instead of the required "unsigned int" type.

Now, using a static_cast on each switch, such as:

case static_cast<unsigned int>(EnumType::SOME):
    ....
    break;
case static_cast<unsigned int>(EnumType::MORE):
    ....
    break;

fixes the syntax error, although casting at each case statement doesn't seem like a good way to do this. Do I really need to cast at each case, or is there a better way?

like image 607
Chris Avatar asked Nov 05 '14 22:11

Chris


People also ask

What is a scoped enum?

Overview. Scoped enums (enum class/struct) are strongly typed enumerations introduced in C++11. They address several shortcomings of the old C-style (C++98) enums, mainly associated with type-safety and name collisions.

Can enum class be used in switch case?

We can use also use Enum keyword with Switch statement. We can use Enum in Switch case statement in Java like int primitive.

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

An enumeration type is still an enumeration type even whether strongly typed or not, and have always worked fine in switch statements.

Where should enums be defined C++?

The best way to define the enum is to declare it in header file. So, that you can use it anywhere you want by including that header file during compilation.


1 Answers

You can solve this by casting the switch variable itself to EnumType:

switch (static_cast<EnumType>(num)) {

(Demo)

The purpose of scoped enums is to make them strongly-typed. To this end, there are no implicit conversions to or from the underlying type. You have to convert either the switch variable or the switch cases. I would suggest converting the switch variable since this requires less code and therefore will make maintenance easier.

IMO the correct solution would be to change the function to accept const EnumType & (or just EnumType) instead.

like image 178
cdhowie Avatar answered Nov 14 '22 23:11

cdhowie