简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM