首页 > 解决方案 > 从整数构造强类型枚举的正确方法

问题描述

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

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

一种解决方案是:

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

但我不喜欢这样,如果我更改了枚举值,我必须记得更新它。

标签: c++c++11enums

解决方案


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

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.


推荐阅读