Mar 262015
 

I just finished the first draft of the implementation of my enum_extend library. It is available via github.

It offers

  • Ranges over all defined enumerated values
  • Filtered ranges over a subset of enumerated values
  • ++ and — pre- and postfix operators
  • Attaching a textual representation to each enumerated value

Some examples:

using enum_extend::range;
using enum_extend::extender;
using enum_extend::filtered_range;

enum class Color
{
  Red = 0, 
  Green = 4, 
  Blue = 8
};

// Let's walk over all defined values
for (auto c : range<Color>()) {
  // ...
}

auto c = Color::Red;
// we can increment as well
++c;

// We iterate in reverse order over all defined values
std::vector<Color> allReverseColors;
std::copy(extender<Color>::rbegin(),
          extender<Color>::rend(), 
          std::back_inserter(allReverseColors));


// Just iterate over all values that match a certain criteria; 
// usefull if the enumerated values are defined as combined bit fields
auto FilterRed = [](Color c) { return c == Color::Red; };
for (auto c : filtered_range<Color>(FilterRed)) {
  // Do just something with red values
}

Only this specialization and the implementation of the operators is necessary:

template <>
enum_extend::extender<Color>::instances
  enum_extend::extender<Color>::all_values = { Color::Red, Color::Green, Color::Blue };


Color& operator++(Color& e) { 
  return enum_extend::extender<Color>::increment(e); 
} 

Color& operator--(Color& e) { 
  return enum_extend::extender<Color>::decrement(e); 
}

Color operator++(Color& e, int) {                                            
  auto tmp = e;                                                            
  enum_extend::extender<Color>::increment(e);
  return tmp;                                                              
}                                                                          

Color operator--(Color& e, int) {                                            
  auto tmp = e;                                                            
  enum_extend::extender<Color>::decrement(e);
  return tmp;                                                              
}                                                                          

There exists a set of macros that simplifies the process of specializing the extender and implementing the operators.

Much more details and examples can be found in this first tutorial

Feedback is welcome!

 

Sorry, the comment form is closed at this time.