从整数

时间:2018-06-04 13:04:46

标签: c++ c++11 enums

如果未映射static_cast<MyEnum>(userInt)userInt可能会导致未定义的行为,那么从用户输入的整数构造强类型枚举的正确方法是什么?

另外,如果输入的值未映射到枚举中,我想将其设置为默认值。

一个解决方案是:

switch (userInt)
{
    case 1:
        selEnum = myEnum1;
        break;
    case 2:
        selEnum = myEnum2;
        break;
    default:
        selEnum = myEnum2;
        error = true;
        break;
}

但我不喜欢我必须记得在更改枚举值时更新它。

1 个答案:

答案 0 :(得分:1)

您可以轻松测试整数是否在基础类型的范围内,然后在枚举值上使用switch

MyEnum convert_from_untrusted_int(int userInt)
{
    using limits = std::numeric_limits<std::underlying_type_t<MyEnum>>>;

    auto const defaultValue = myEnum2;

    if (userInt < limits.min() || userInt > limits.max())
        return defaultValue;

    auto const e = MyEnum(userInt);
    switch (e) {
      case myEnum1:
      case myEnum2:  // compiler will warn if we miss one
        return e;
    }
    // we only get here if no case matched
    return defaultValue;
}

这取决于您是否使用了足够的编译器警告,当然,switch会记录缺少的枚举数。

相关问题