C++11 scoped enumerators (enum class syntax) do not convert to integers so they cannot be used directly as array indexes.
What’s the best way to get the benefit of scoping when using them in this fashion?
I’ve provided a couple answers, but please add more ideas!
Solution 1: Operator overloading.
This is my current favorite. Overload unary
operator+andoperator++to explicitly convert to integral type and increment within the enumerated type, respectively.Using an
enumeration_traitstemplate, overloads can be activated rather than copying boilerplate code. But the boilerplate is just a couple one-liners.Library code (templates, see below for non-template alternative):
User code:
Boilerplate code (if not using library, follows
enumdefinition):Solution 2: Manual scoping.
Scoped enumerator syntax also works on unscoped (non
enum class) enumerations, which do implicitly convert toint. Hiding the enumeration inside a class or namespace and importing it withtypedeforusingmakes it pseudo-scoped.But if multiple enumerations go into the same namespace, the enumerator names may collide, so you might as well use a class (or many namespaces).
This has some benefits. It works with C++03, but only with syntax
ducks_enum::count. The enumerators are unscoped inside the struct, and it can be used as a base for any class that makes frequent use of the enumerators.