c++ - 从整数构造强类型枚举的正确方法
问题描述
鉴于如果未映射static_cast<MyEnum>(userInt)
可能导致未定义行为,那么从用户输入的整数构造强类型枚举的正确方法是什么?userInt
另外,如果输入的值未映射到枚举中,我想将其设置为默认值。
一种解决方案是:
switch (userInt)
{
case 1:
selEnum = myEnum1;
break;
case 2:
selEnum = myEnum2;
break;
default:
selEnum = myEnum2;
error = true;
break;
}
但我不喜欢这样,如果我更改了枚举值,我必须记得更新它。
解决方案
您可以轻松测试整数是否在基础类型的范围内,然后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
.
推荐阅读
- html - 在css中为按钮着色
- java - /api/jsonws 提供的 Liferay JSON Web 服务对任何用户开放访问
- python - 文件从 python.exe 运行
- c# - sqlite 异常已被调用的目标抛出
- angular - 为什么我的测验应用程序中的问题之间的导航不起作用?
- google-chrome-extension - chrome.bookmarks.onChildrenReordered 何时被解雇?
- java - Maven 无法创建本地存储库
- mfc - 自定义标量值类型
- python - 我想找出一个月内离开特定年龄组的平均频率
- python - 具有多个参数的 Python makefile