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;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top