use*_*501 11 c++ casting enum-class
我有一个像这样的枚举类:
    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?
Fre*_*pin 13
这是因为"枚举类"是"强类型",因此不能隐式转换为任何其他类型.http://en.wikipedia.org/wiki/C%2B%2B11#Strongly_typed_enumerations
jua*_*nza 11
因为C++ 11 强类型枚举不能通过设计隐式转换为整数类型.底层类型是a的unsigned int事实并不意味着枚举的类型unsigned int.是的BinaryInstructions.
但是你实际上并不需要转换因为arg是无符号的int,你需要一个强制转换,但static_cast为了清晰起见你应该更喜欢:
switch(arg)
{
    case static_cast<unsigned int>(BinaryInstructions::END_INSTRUCTION) :
        return "end";
    break;
}
| 归档时间: | 
 | 
| 查看次数: | 17950 次 | 
| 最近记录: |