Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 500
FreelanceConsultant Avatar asked Feb 19 '13 21:02

FreelanceConsultant


2 Answers

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

like image 141
Freddie Chopin Avatar answered Oct 31 '22 12:10

Freddie Chopin


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;
}
like image 31
juanchopanza Avatar answered Oct 31 '22 11:10

juanchopanza