简体   繁体   中英

What is the safest way to cast a given value to enum in C++

I want to check if a given value belongs to MyEnum, which type is uint8. The given value could be uint8 or not, eg, it could also be int, uint16, etc.

#include <iostream>

int main()
{
    enum class MyEnum : std::uint8_t
    {
        A = 0,
        B = 1,
        C = 2,
        D = 3,
    };

    int x = 256;  // Note that this is not uint8
    switch(MyEnum(x))
    {
    case MyEnum::A:
    case MyEnum::B:
    case MyEnum::C:
    case MyEnum::D:
        std::cout << "OK" << std::endl;
        break;
    default:
        std::cout << "NOT OK" << std::endl;
    }

    return 0;
}

Output

OK

As you can see, 256 is casted to uint8_t 0, which is MyEnum::A.

My Question

What is the standard way in C++ to check if a given value belongs to an enum? Given the example above, is there any other way than just checking the value explicitly before casting?

if (x < 0 || x > 255)
{
    // Do not cast to MyEnum
};
else
{
    // Cast to MyEnum
}

You want to check std::numeric_limits<underlying_type_t<MyEnum>>::max() , which will be 255 for your std::uint8_t .

As for checking whether it matches one of the named values, this isn't possible. You cannot enumerate over names.

Note that even without an underlying type, any bitwise combination of enumerators is also valid, as is 0. Easiest to explain with an example: if you have {READ=1, WRITE=2, EXECUTE=4} then 1|2|4==7 is also in range.

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