简体   繁体   English

打开范围枚举

[英]Switching on scoped enum

I am trying to switch on a scoped-enum with the type unsigned int: 我试图打开unsigned int类型的scoped-enum:

The enum is defined as: 枚举定义为:

const enum struct EnumType : unsigned int { SOME = 1, MORE = 6, HERE = 8 };

I receive a const unsigned int reference and I am trying to check that value against the enum values. 我收到一个const unsigned int引用,我试图根据枚举值检查该值。

void func(const unsigned int & num)
{
    switch (num)
    {
    case EnumType::SOME:
        ....
        break;
    case EnumType::MORE:
        ....
        break;

    ....

    default:
        ....
    }
}

This results in a syntax error: Error: This constant expression has type "EnumType" instead of the required "unsigned int" type. 这会导致语法错误: Error: This constant expression has type "EnumType" instead of the required "unsigned int" type.

Now, using a static_cast on each switch, such as: 现在,在每个开关上使用static_cast ,例如:

case static_cast<unsigned int>(EnumType::SOME):
    ....
    break;
case static_cast<unsigned int>(EnumType::MORE):
    ....
    break;

fixes the syntax error, although casting at each case statement doesn't seem like a good way to do this. 修复了语法错误,虽然在每个case语句中进行转换似乎不是一个好方法。 Do I really need to cast at each case, or is there a better way? 我是否真的需要在每个案例中施放,还是有更好的方法?

You can solve this by casting the switch variable itself to EnumType : 您可以通过将switch变量本身转换为EnumType来解决此问题:

switch (static_cast<EnumType>(num)) {

( Demo ) 演示

The purpose of scoped enums is to make them strongly-typed. 范围枚举的目的是使它们具有强类型。 To this end, there are no implicit conversions to or from the underlying type. 为此,基础类型没有隐式转换。 You have to convert either the switch variable or the switch cases. 您必须转换开关变量或开关案例。 I would suggest converting the switch variable since this requires less code and therefore will make maintenance easier. 我建议转换开关变量,因为这需要更少的代码,因此将使维护更容易。

IMO the correct solution would be to change the function to accept const EnumType & (or just EnumType ) instead. IMO正确的解决方案是将函数更改为接受const EnumType & (或仅仅是EnumType )。

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

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