c++ - 允许枚举类的基于范围的 For?

标签 c++ for-loop c++11 enums

我有一个循环代码块,我循环遍历 enum 类的所有成员。

与新的基于范围的for相比,我目前使用的for循环看起来非常笨拙。

有什么方法可以利用新的 C++11 功能来减少当前 for 循环的冗长性?

我想改进的当前代码:

enum class COLOR
{
    Blue,
    Red,
    Green,
    Purple,
    First=Blue,
    Last=Purple
};

inline COLOR operator++( COLOR& x ) { return x = (COLOR)(((int)(x) + 1)); }

int main(int argc, char** argv)
{
  // any way to improve the next line with range-based for?
  for( COLOR c=COLOR::First; c!=COLOR::Last; ++c )
  {
    // do work
  }
  return 0;
}

换句话说,如果我能做这样的事情就好了:

for( const auto& c : COLOR )
{
  // do work
}

最佳答案

我个人不喜欢为枚举重载 ++ 运算符。通常递增一个枚举值并没有真正的意义。真正需要的只是一种迭代枚举的方法。

下面是一个支持迭代的通用Enum类。它是功能性的,但不完整。真正的实现会很好地限制对构造函数的访问并添加所有迭代器特征。

#include <iostream>

template< typename T >
class Enum
{
public:
   class Iterator
   {
   public:
      Iterator( int value ) :
         m_value( value )
      { }

      T operator*( void ) const
      {
         return (T)m_value;
      }

      void operator++( void )
      {
         ++m_value;
      }

      bool operator!=( Iterator rhs )
      {
         return m_value != rhs.m_value;
      }

   private:
      int m_value;
   };

};

template< typename T >
typename Enum<T>::Iterator begin( Enum<T> )
{
   return typename Enum<T>::Iterator( (int)T::First );
}

template< typename T >
typename Enum<T>::Iterator end( Enum<T> )
{
   return typename Enum<T>::Iterator( ((int)T::Last) + 1 );
}

enum class Color
{
   Red,
   Green,
   Blue,
   First = Red,
   Last = Blue
};

int main()
{
   for( auto e: Enum<Color>() )
   {
      std::cout << ((int)e) << std::endl;
   }
}

关于c++ - 允许枚举类的基于范围的 For?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8498300/

相关文章:

c++ - 防止 std::atomic 溢出

c++ - 在 Code::Blocks 中构建一个 wxWidgets 程序

c++ - MongoDB C++ Legacy 驱动程序 - 如何使用 UNIX 域套接字进行连接

Matlab:使用矩阵运算而不是 for 循环

javascript - 循环确定 selectedIndex 不起作用?

python - 使用 for 循环将两个列表中的数据插入到字典中

c++ - C++中的堆排序实现

C++ unique_ptr 从派生到基础的转换

C++11 模板函数 "implicity"将 bitset<N> 转换为 "unsigned long"

c++ - 小数因子的缩减数组