繁体   English   中英

打开范围枚举

[英]Switching on scoped enum

我试图打开unsigned int类型的scoped-enum:

枚举定义为:

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语句中进行转换似乎不是一个好方法。 我是否真的需要在每个案例中施放,还是有更好的方法?

您可以通过将switch变量本身转换为EnumType来解决此问题:

switch (static_cast<EnumType>(num)) {

演示

范围枚举的目的是使它们具有强类型。 为此,基础类型没有隐式转换。 您必须转换开关变量或开关案例。 我建议转换开关变量,因为这需要更少的代码,因此将使维护更容易。

IMO正确的解决方案是将函数更改为接受const EnumType & (或仅仅是EnumType )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM