简体   繁体   中英

Enum Class “could not convert to unsigned int”

I have an enum class like this:

    typedef unsigned int binary_instructions_t;

    enum class BinaryInstructions : binary_instructions_t
    {
        END_INSTRUCTION = 0x0,

        RESET,

        SET_STEP_TIME,
        SET_STOP_TIME,
        START,

        ADD
    };

And I am trying to use the members of the enum in a switch statement like this:

const std::string& function(binary_instructions_t arg, bool& error_detect)
{
    switch(arg)
    {
        case (unsigned int)BinaryInstructions::END_INSTRUCTION:
            return "end";
        break;
    }
    translate_error = true;
    return "ERROR";
}

Why is the cast to (unsigned int) required when the underlying type is already an unsigned int ?

That's because "enum class" is "strongly-typed", so not implicitly convertible to any other type. http://en.wikipedia.org/wiki/C%2B%2B11#Strongly_typed_enumerations

Because C++11 strongly typed enums are not implicitly convertible to integral types by design. The fact that the underlying type is an unsigned int doesn't mean the type of the enum is unsigned int . It is BinaryInstructions .

But you don't actually need the conversion anyway Since arg is an unsigned int, you need a cast, but you should prefer a static_cast for clarity:

switch(arg)
{
    case static_cast<unsigned int>(BinaryInstructions::END_INSTRUCTION) :
        return "end";
    break;
}

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