Note that there are some explanatory texts on larger screens.

plurals
  1. POWhich Typesafe Enum in C++ Are You Using?
    text
    copied!<p>It is common knowledge that built-in enums in C++ are not typesafe. I was wondering which classes implementing typesafe enums are used out there... I myself use the following "bicycle", but it is somewhat verbose and limited:</p> <p>typesafeenum.h:</p> <pre><code>struct TypesafeEnum { // Construction: public: TypesafeEnum(): id (next_id++), name("") {} TypesafeEnum(const std::string&amp; n): id(next_id++), name(n) {} // Operations: public: bool operator == (const TypesafeEnum&amp; right) const; bool operator != (const TypesafeEnum&amp; right) const; bool operator &lt; (const TypesafeEnum&amp; right) const; std::string to_string() const { return name; } // Implementation: private: static int next_id; int id; std::string name; }; </code></pre> <p>typesafeenum.cpp:</p> <pre><code>int TypesafeEnum::next_id = 1; bool TypesafeEnum::operator== (const TypesafeEnum&amp; right) const { return id == right.id; } bool TypesafeEnum::operator!= (const TypesafeEnum&amp; right) const { return !operator== (right); } bool TypesafeEnum::operator&lt; (const TypesafeEnum&amp; right) const { return id &lt; right.id; } </code></pre> <p>Usage:</p> <pre><code>class Dialog { ... struct Result: public TypesafeEnum { static const Result CANCEL("Cancel"); static const Result OK("Ok"); }; Result doModal(); ... }; const Dialog::Result Dialog::Result::OK; const Dialog::Result Dialog::Result::CANCEL; </code></pre> <p><strong>Addition:</strong> I think I should have been more specific about the requirements. I'll try to summarize them:</p> <p>Priority 1: Setting an enum variable to an invalid value should be impossible (a compile-time error) with no exceptions.</p> <p>Priority 2: Converting an enum value to/from an int should be possible with a single explicit function/method call.</p> <p>Priority 3: As compact, elegant and convenient declaration and usage as possible</p> <p>Priority 4: Converting enum values to and from strings.</p> <p>Priority 5: (Nice to have) Possibility to iterate over enum values.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload