PERA Software Solutions GmbH

Replace enums with classes in C++

Replace enums with classes in C++

Problem

The C++ enum types have some shortcomings like: So the last time I needed the above features I remembered an article I've read about how Java could 'simulate' enums before they became part of the language with the Replace Enums with Classes. if we try to implement the pattern in C++ then we get something like this: // Color.cpp class Color { public: static const Color Red; static const Color Green; static const Color Blue; constexpr int value() const noexcept { return value_; } constexpr const char *name() const noexcept { return name_; } constexpr bool operator == (const Color &other) const noexcept { return value_ == other.value_; } constexpr bool operator < (const Color &other) const noexcept { return value_ < other.value_; } private: template <std::size_t SIZE> constexpr Color(int value, const char (&name)[SIZE]) noexcept : value_(value), name_(name) { } int value_; const char *name_; }; const Color Color::Red( 0, "Red"); const Color Color::Green(1, "Green"); const Color Color::Blue( 2, "Blue"); Some things to note: With this we can already write code like this: // ColorUsage.cpp int main(int, char *[]) { Color color = Color::Blue; color = Color::Green; if (color == Color::Blue) { cout << color.name() << endl; } return 0; }

Notes

The cppreference.com website lists a couple of enum libraries.