"枚举类"的增加和减少

Iva*_*lov 21 c++ enums c++11

我们知道,enumC++ 03中的递增和递减是非法的,因为C++ 03 enum可能不是连续的.但是C++ 11标准引入了新的enum class结构,根据维基百科的说法,它更加类型安全,因为它不是基于任何简单的可数类型构建的.所以现在,如果我们有一个枚举值的有界列表,我们可以编写类似的东西

enum class Colors { Black, Blue, White };
// ...
Colors color = Colors::White;
color++;
Run Code Online (Sandbox Code Playgroud)

并且将它正常工作(例如增量White将返回Black和递减Black将返回White)?

如果我们不能写出这样的代码,你知道无论是从任何行为般类boost或Qt为我们提供这个功能(正确输入和递减)?

Dre*_*ann 24

它会正常工作吗?

编号 enum不是按照您默认描述的方式"环绕"的.

并且C++ 11 enum class不保证连续值,与您为C++ 03描述的相同enum.

您可以定义特定枚举的包装行为. 此解决方案假定值是连续的,就像您描述的枚举一样.

enum class Colors { Black, Blue, White, END_OF_LIST };

// Special behavior for ++Colors
Colors& operator++( Colors &c ) {
  using IntType = typename std::underlying_type<Colors>::type
  c = static_cast<Colors>( static_cast<IntType>(c) + 1 );
  if ( c == Colors::END_OF_LIST )
    c = static_cast<Colors>(0);
  return c;
}

// Special behavior for Colors++
Colors operator++( Colors &c, int ) {
  Colors result = c;
  ++c;
  return result;
}
Run Code Online (Sandbox Code Playgroud)

  • 有没有一种方法可以在没有强制转换的情况下实现`++`?我想不出任何,但这个实现困扰我.演员通常表示出现了错误,并且必须有充分的理由让他们使用.我希望这种语言能够实现`++`,而不必强制使用特定的类型. (4认同)
  • @icepack那是因为没有.因此,在大多数情况下,enum不是特别有用的结构. (3认同)