14

次のような列挙型クラスがあります。

    typedef unsigned int binary_instructions_t;

    enum class BinaryInstructions : binary_instructions_t
    {
        END_INSTRUCTION = 0x0,

        RESET,

        SET_STEP_TIME,
        SET_STOP_TIME,
        START,

        ADD
    };

そして、次のような switch ステートメントで列挙型のメンバーを使用しようとしています。

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";
}

(unsigned int)基になる型が既に であるのに、なぜ へのキャストが必要なのunsigned intですか?

4

2 に答える 2

16

これは、「列挙型クラス」が「厳密に型指定されている」ため、他の型に暗黙的に変換できないためです。http://en.wikipedia.org/wiki/C%2B%2B11#Strongly_typed_enumerations

于 2013-02-19T21:45:45.883 に答える
13

C++11の厳密に型指定された列挙型は、設計上、暗黙的に整数型に変換できないためです。基になる型が であるという事実はunsigned int、列挙型の型が であるという意味ではありませんunsigned int。ですBinaryInstructions

ただし、実際には変換は必要ありません。は unsigned int であるためarg、キャストが必要ですが、static_cast明確にするためにa を優先する必要があります。

switch(arg)
{
    case static_cast<unsigned int>(BinaryInstructions::END_INSTRUCTION) :
        return "end";
    break;
}
于 2013-02-19T21:44:57.570 に答える