For a small project I'm working on, I've been looking for an iterable enum
-like class in C++, since neither C-style nor scoped enum
s seem to support iteration in a way that isn't hack-y. I stumbled across this (relatively) old article, from which I've drawn inspiration to create a robust Enum
class supporting iteration and C++11 features.
The client simply creates a DEnum
class, which includes the desired enum
items as static const members, inheriting from this Enum
class. This prevents code using DEnum
from creating new items. Local object copies of the enum
items can be created through the default copy and copy-assignment ctors. I've also added a function that allows creation of a local subset of the enum
items, which also supports iteration (including using range-for syntax). The class should be type-safe in preventing type conversion of its members and instantiated copies.
I'm just looking for any tips on how I could implement this better. Does this code follow C++11 best practices? Are there any problems I've overlooked?
// enum.h
#ifndef ENUM_H_
#define ENUM_H_
#include <algorithm>
#include <functional>
#include <initializer_list>
#include <iostream>
#include <set>
template <class T>
class Enum {
private:
// Comparator used to determine enum item ordering
struct EnumLTComparator {
bool operator() (const T* e1, const T* e2) {
return e1->value() < e2->value();
}
};
public:
typedef std::set<const T*, EnumLTComparator> ItemsSet;
typedef typename ItemsSet::size_type set_size_type;
typedef typename ItemsSet::const_iterator const_iterator;
typedef typename ItemsSet::const_reverse_iterator const_r_iterator;
int value() const { return value_; }
static set_size_type size() { return items_.size(); }
// Iteration
static const_iterator begin() { return items_.cbegin(); }
static const_iterator end() { return items_.cend(); }
static const_r_iterator rbegin() { return items_.crbegin(); }
static const_r_iterator rend() { return items_.crend(); }
bool operator== (T e2) const {return this->value() == e2.value();}
// Return a set which contains pointers to any number of unique enum items
static ItemsSet Subset(std::initializer_list<T> items) {
ItemsSet subset;
for (auto i: items) {
subset.insert(CorrespondingEnum(i.value()));
}
return subset;
}
protected:
// Constructors
explicit Enum(int value): value_(value) {
// Warn clients if they try to add multiple items with the same value
if (IsValidValue(value)) {
std::cerr << "The value \'" << value << "\' has been assigned to "
<< "multiple items in this enum. All duplicates are omitted "
<< "from the set." << std::endl;
return;
}
// This cast seems ugly, since the object being constructed by the
// inheriting class will already be of type T, but I don't see any
// way around this.
items_.insert(static_cast<T*>(this));
}
// Compiler-generated copy and copy-assign ctors generate local copies of
// the static enum items
private:
static const T* CorrespondingEnum(int value) {
auto EnumPredicateCorresponds = [value](const T* elem) -> bool {
return elem->value() == value;
};
const_iterator it = find_if(items_.begin(),
items_.end(),
EnumPredicateCorresponds);
return (it != items_.end()) ? *it : nullptr;
}
static bool IsValidValue(int value) {
return CorrespondingEnum(value) != nullptr;
}
int value_;
static ItemsSet items_;
};
#endif
And a client would use this class as follows:
// color.h
#ifndef COLOR_H_
#define COLOR_H_
#include "enum.h"
class Color: public Enum<Color> {
public:
using Enum::Enum; //Color::Color(int) is still protected
static const Color blue;
static const Color green;
static const Color red;
static const Color white;
static const Color yellow;
static const Color multicolor;
static const Color hidden;
};
#endif
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// color.cc
#include "color.h"
#include "enum.h"
// I would prefer not to require this, but I don't see a way around it
template<>
typename Enum<Color>::ItemsSet Enum<Color>::items_{};
const Color Color::blue(0);
const Color Color::green(1);
const Color Color::red(2);
const Color Color::white(3);
const Color Color::yellow(4);
const Color Color::multicolor(5);
const Color Color::hidden(6);
Finally, some testing with cout:
#include <iostream>
#include "color.h"
using std::cout;
using std::endl;
int main() {
cout << Color::size() << endl; //7
for (auto iCol = Color::begin(); iCol != Color::end(); ++iCol) {
cout << (*iCol)->value() << endl;
}
/* 0
* 1
* 2
* 3
* 4
* 5
* 7
*/
cout << (**(Color::begin()) == Color::blue) << endl; //1
cout << (**(Color::begin()) == Color::red) << endl; //0
cout << (**(Color::rbegin()) == Color::hidden) << endl; //1
cout << (**(Color::rbegin()) == Color::yellow) << endl; //0
auto subset = Color::Subset({Color::blue, Color::red});
cout << (**(subset.begin()) == Color::blue) << endl; //1
cout << (**(subset.rbegin()) == Color::red) << endl; //0
for (auto iCol: subset) {
cout << iCol->value() << endl;
// 0
// 2
}
//Color mauve(2); //Error: Color::Color is protected
//Color *col = &(Color::red); //Error: can't convert from 'const Color*'
// to Color*'
}