【问题标题】:C++11 enum class: plus int failed to compile, why?C++11枚举类:plus int编译失败,为什么?
【发布时间】:2018-04-07 11:33:39
【问题描述】:

我有一个快速的代码片段:

#include<iostream>
using namespace std;
enum class A:int {
    u=1,
    v=2,
    w=3
};
template<A value>
int nextEnum(){
    return value+1;
}
int main() {
    nextEnum<A::u>();
    return 0;
}

编译失败:

clang++ testenum.cpp -std=c++11
testenum.cpp:10:17: error: invalid operands to binary expression ('A' and 'int')
    return value+1;

好吧,我已经将 A 声明为“int”枚举,为什么它不能用 int 来“+”?如何解决?

【问题讨论】:

  • 枚举的“继承”更多是针对范围和大小,而不是针对实际继承。此外,通过使用scoped enumerations,类型名称A强类型。它不能隐式转换为其他整数类型,您必须显式地进行转换。

标签: c++ class c++11 enums int


【解决方案1】:

添加

int operator+(A a, int b) {
    return a + b;
}

将修复此错误!在 Windows VS2017 上测试通过

【讨论】:

    【解决方案2】:

    枚举类是强类型的,不会隐式转换为 int。为此,您需要在枚举类中定义转换为 int 或“+”运算符。

    【讨论】:

      【解决方案3】:

      enum class 不能隐式转换为整数。你必须使用static_cast,例如:

      template <A value>
      A nextEnum() {
        return static_cast<A>(static_cast<int>(value) + 1);
      }
      

      【讨论】:

      • 事实上,enum class全部意义 是它不会隐式地与int 相互转换。 (嗯,枚举并没有被注入到包含的命名空间中)。
      猜你喜欢
      • 2019-11-08
      • 1970-01-01
      • 2015-03-09
      • 1970-01-01
      • 2013-05-07
      • 2013-05-14
      • 1970-01-01
      相关资源
      最近更新 更多