允许使用枚举类的基于范围的For?

时间:2011-12-14 00:49:32

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

我有一个经常出现的代码块,我循环遍历enum class的所有成员。

与新for相比,我目前使用的range-based 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
}

11 个答案:

答案 0 :(得分:49)

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

下面是支持迭代的通用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;
   }
}

答案 1 :(得分:33)

enum class Color {
    blue,
    red,
    green = 5,
    purple
};
const std::array<Color,4> all_colors = {Color::blue, Color::red, Color::green, Color::purple};

然后:

for (Color c : all_colors) {
    //...
}

很多时候我会像这样使用它,我想要一个&#39;无值:

// Color of a piece on a chess board
enum class Color {
    white,
    black,
    none
};
const std::array<Color,3> colors = {Color::white, Color::black};

template <typename CONTAINER>
bool has_item (CONTAINER const & c, typename CONTAINER::const_reference v) {
    return std::find(c.begin(), c.end(), v) != c.end();
}

bool is_valid (Color c) {
    return has_item(colors, c) || c == Color::none;
}

bool do_it (Color c) {
    assert(has_item(colors, c)); // here I want a real color, not none
    // ...
}

bool stop_it (Color c) {
    assert(is_valid(c));         // but here I just want something valid
    // ...
}

答案 2 :(得分:30)

使用枚举本身作为迭代器迭代枚举是一个糟糕的想法,我建议使用实际的迭代器,如deft_code的答案。但如果这真的是你想要的那样:

COLOR operator++(COLOR& x) {
    return x = (COLOR)(std::underlying_type<COLOR>::type(x) + 1); 
}

COLOR operator*(COLOR c) {
    return c;
}

COLOR begin(COLOR r) {
    return COLOR::First;
}

COLOR end(COLOR r) {
    COLOR l=COLOR::Last;
    return ++l;
}

int main() { 
    //note the parenthesis after COLOR to make an instance
    for(const auto& c : COLOR()) {
        //do work
    }
    return 0;
}

在此工作:http://ideone.com/cyTGD8

<小时/> 在迭代器方面,最简单的方法就是:

extern const COLOR COLORS[(int)COLOR::Last+1];
const COLOR COLORS[] = {COLOR::Blue, COLOR::Red, COLOR::Green, COLOR::Purple};

int main() { 
    for(const auto& c : COLORS) {
        //do work
    }
    return 0;
}

如下所示:http://ideone.com/9XadVt

(如果颜色的数量与数组中的元素数量不匹配,则数组的单独声明和定义会使编译错误。非常容易安全检查。)

答案 3 :(得分:4)

你可以用boost :: mpl做一些聪明的事,粗略的版本可能看起来像:

#include <typeinfo>

// ---------------------------------------------------------------------------|
// Boost MPL
// ---------------------------------------------------------------------------|
#include <boost/mpl/for_each.hpp>
#include <boost/mpl/iterator_range.hpp>
#include <boost/mpl/range_c.hpp>

namespace mpl = boost::mpl;

using namespace std;

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

struct enumValPrinter
{
    template< typename T >
    void operator() (const T&)
    {
        cout << "enumValPrinter with: " << typeid( T ).name() << " : " 
             << T::value << "\n";
    }
};

int main(int, char**)
{
    typedef mpl::range_c< int, static_cast<int>( COLOR::Blue ), 
                            static_cast<int>( COLOR::Last ) > Colors;
    mpl::for_each< Colors >( enumValPrinter() );
    return 0;
}

答案 4 :(得分:3)

这是一个经过测试的例子(GCC 4.6.1):

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

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

COLOR operator*(COLOR c) {return c;}

COLOR begin(COLOR r) {return COLOR::First;}
// end iterator needs to return one past the end!
COLOR end(COLOR r)   {return COLOR(int(COLOR::Last) + 1);}


int main()
{
    for (const auto& color : COLOR()) std::cout << int(color); //0123
    return 0;
}

答案 5 :(得分:2)

我非常喜欢这个想法并经常希望它。

我看到的问题是当枚举项有重复的数值时会发生什么。我在上面看到的所有实现都需要转换为整数类型和++。最终,我认为可能需要语言支持才能在所有情况下真正迭代每个项目。尽管我不太反对这一点,但它不需要有First,Last或Begin,End。这就像为容器寻找begin()end()。

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

编号从Mauve开始。

答案 6 :(得分:2)

如果您是一个可怕的人,您可以使用预处理器获得此行为,例如:

#include <vector>
#include <cstdio>

#define ENUM_NAME COLOR
#define ENUM_VALUES \
    ENUM_VALUE(Blue) \
    ENUM_VALUE(Red) \
    ENUM_VALUE(Green) \
    ENUM_VALUE(Purple)

// This block would be a #include "make_iterable_enum.h"
#define ENUM_VALUE(v) v,
enum class ENUM_NAME {ENUM_VALUES};
#undef ENUM_VALUE
#define ENUM_VALUE(v) ENUM_NAME::v,
#define VECTOR_NAME(v) values_ ## v
#define EXPAND_TO_VECTOR_NAME(v) VECTOR_NAME(v)
const std::vector<ENUM_NAME> EXPAND_TO_VECTOR_NAME(ENUM_NAME){ENUM_VALUES};
#undef ENUM_VALUE
#undef ENUM_NAME
#undef ENUM_VALUES
#undef VECTOR_NAME
#undef EXPAND_TO_VECTOR_NAME
// end #included block

int main() {
    for (auto v : COLOR_values) {
        printf("%d\n", (int)v);
    }
}

通过微小的修改,这也可以支持例如。 ENUM_SETVALUE(蓝色,4)并从例如制作const地图。颜色::蓝色到&#34;蓝色&#34;。反之亦然。

我希望标准刚刚将这些功能构建为枚举类的选项。没有一种解决方法是好的。

答案 7 :(得分:2)

我确信您可以迭代C ++初始化列表的成员,所以我认为我过去已经这样做过了:

enum class Color {Red, Green, Blue};

for (const Color c : {Color::Red, Color::Green, Color::Blue})
{
}

这是否存在问题,我不知道,但我认为我会建议它,因为它很简洁,但如果有很多颜色则不理想。

答案 8 :(得分:1)

无论您是否赞成递增枚举,有时都会有用。因此,这是一种简单的方法:

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

COLOR c;

++( *reinterpret_cast<int*>( &c));

没有开销,因为编译器将负责强制转换和取消引用。根据需要添加范围检查或其他功能。

答案 9 :(得分:0)

作为@deft_code答案的修改,您无需在First中定义Lastenum class,只需为模板化{{1}添加两个参数}类。

Enum

答案 10 :(得分:0)

扩展,但也简化了@rubenvb的先前答案(哇,2016年12月)。

要轻松地遍历颜色,可以使用一种方法为每种颜色提供数字或字符串值(例如,当您希望在某些Xml文件中提供值时)。

enum class COLOR
{
    Blue,
    Red,
    Green,
    Purple,
};

std::map<COLOR,std::string> colors = {
 {COLOR::Blue,"Blue"},
 {COLOR::Red,"Red"},
 {COLOR::Green,"Green"},
 {COLOR::Purple,"Purple"}, // yay Whoopi, great movie
};

for (auto pair : colors) {
  do_something_with_color(pair.first);
  and_maybe_even_do_something_with_color_value(pair.second);
}

维护工作并不困难,只需确保您将所有枚举都包含在地图中即可。

相关问题