【发布时间】:2014-11-05 22:19:27
【问题描述】:
我正在尝试打开类型为 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.
现在,在每个开关上使用static_cast,例如:
case static_cast<unsigned int>(EnumType::SOME):
....
break;
case static_cast<unsigned int>(EnumType::MORE):
....
break;
修复了语法错误,尽管在每个 case 语句中进行强制转换似乎不是一个好方法。我真的需要在每种情况下都进行投射,还是有更好的方法?
【问题讨论】:
-
在我看来,强类型枚举的全部意义在于它们是……好吧,强类型,所以没有隐式转换。所以是的,你确实需要投射。编辑:我现在看到你不是在问你是否需要投射,而是你是否需要为每个案例投射。对不起,我的错。
标签: c++ visual-c++ c++11 enums switch-statement