121*_*21c 7 c++ enums switch-statement visual-c++ c++11
我试图打开unsigned int类型的scoped-enum:
枚举定义为:
const enum struct EnumType : unsigned int { SOME = 1, MORE = 6, HERE = 8 };
Run Code Online (Sandbox Code Playgroud)
我收到一个const unsigned int引用,我试图根据枚举值检查该值.
void func(const unsigned int & num)
{
switch (num)
{
case EnumType::SOME:
....
break;
case EnumType::MORE:
....
break;
....
default:
....
}
}
Run Code Online (Sandbox Code Playgroud)
这会导致语法错误: Error: This constant expression has type "EnumType" instead of the required "unsigned int" type.
现在,static_cast在每个开关上使用a ,例如:
case static_cast<unsigned int>(EnumType::SOME):
....
break;
case static_cast<unsigned int>(EnumType::MORE):
....
break;
Run Code Online (Sandbox Code Playgroud)
修复了语法错误,虽然在每个case语句中进行转换似乎不是一个好方法.我是否真的需要在每个案例中施放,还是有更好的方法?
cdh*_*wie 10
您可以通过将switch变量本身转换为EnumType:
switch (static_cast<EnumType>(num)) {
Run Code Online (Sandbox Code Playgroud)
(演示)
范围枚举的目的是使它们具有强类型.为此,基础类型没有隐式转换.您必须转换开关变量或开关案例.我建议转换开关变量,因为这需要更少的代码,因此将使维护更容易.
IMO正确的解决方案是将函数更改为接受const EnumType &(或仅仅EnumType).