我正在尝试使用类型为unsigned int的作用域枚举进行开关操作:
枚举定义如下:
const enum struct EnumType : unsigned int { SOME = 1, MORE = 6, HERE = 8 };
我收到了一个 const unsigned int 的引用,我正在尝试将该值与枚举值进行比较。
void func(const unsigned int & num)
{
switch (num)
{
case EnumType::SOME:
....
break;
case EnumType::MORE:
....
break;
....
default:
....
}
}
这会导致语法错误:Error: This constant expression has type "EnumType" instead of the required "unsigned int" type.
现在,可以对每个switch使用static_cast
,例如:
case static_cast<unsigned int>(EnumType::SOME):
....
break;
case static_cast<unsigned int>(EnumType::MORE):
....
break;
修复了语法错误,尽管在每个case语句中进行强制转换似乎不是一个好的解决方法。我是否真的需要在每个case中进行强制转换,还是有更好的方法?