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 th
The original question related to using the enumeration as an array index. Instead of trying to turn the enumeration into an index for an array, build an array that accepts the enumeration as its index:
template (largest_enum)>
class EnumeratedArray {
ValueType underlying [static_cast (largest_enum)];
public:
using value_type = ValueType;
using enumeration_type = Enumeration;
EnumeratedArray () {
for (int i = 0; i < largest; i++) {
underlying [i] = ValueType {};
}
}
inline ValueType &operator[] (const Enumeration index) {
assert (static_cast (index) >= 0 && static_cast (index) < largest);
return underlying [static_cast (index)];
}
inline const ValueType &operator[] (const Enumeration index) const {
assert (static_cast (index) >= 0 && static_cast (index) < largest);
return underlying [static_cast (index)];
}
};
So now, with the earlier ducks example:
enum class ducks { huey, dewey, louie, count };
EnumeratedArray duck_height;
duck_height [ducks::huey] = 42.0;
Had ducks values been capitalized differently, the size could default:
enum class Ducks { Huey, Dewey, Louie, Count };
EnumeratedArray duck_height;
duck_height [Ducks::Huey] = 42.0;
In addition to avoiding enum contortions, since the to-index conversion is hidden in the implementation, the enum doesn't risk erroneously becoming an integer at other points in your code, nor can you inadvertently index the array via integer.
EnumeratedArray is used in pianod2, in src/common. A more extensive version there includes template magic to only explicitly default-initialize plain-old datatypes, a constructor to initialize all elements to a specified value, and doc comments.