【问题标题】:Switching on scoped enum打开作用域枚举
【发布时间】: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


【解决方案1】:

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

switch (static_cast<EnumType>(num)) {

(Demo)

作用域枚举的目的是使它们成为强类型。为此,没有与基础类型之间的隐式转换。您必须转换开关变量或开关案例。我建议转换 switch 变量,因为这需要更少的代码,因此会使维护更容易。

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

【讨论】:

    猜你喜欢
    • 2012-12-13
    • 2015-03-01
    • 1970-01-01
    • 2020-12-16
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多