Type safe enum class replace with normal class.
Used as an index (key) type for continuous containers like std::vector / std::array instead of std::map etc.
Pro: Fun.
Con: dynamic indice. myEnumIdx.somedata = 100000; can blow up the hole thing.
For static enum array see
http://fcppt.org/da/dcf/classfcppt_1_1container_1_1enum__array.html#af01f0518d2f63f4fd47eb5c510855c63
http://fcppt.org/d6/ddd/group__fcpptenum.html
#include <vector>
template<typename Key, typename Value>
class EnumArray {
public:
Value & operator[](const Key& key) {
return data[key];
}
private:
std::vector<Value> data;
};
class EnumType {
public:
int someData = 0;
private:
operator int() const {
return someData;
}
template<typename EnumType, typename>
friend class EnumArray;
};
class EnumType2 {
public:
int someData = 0;
private:
operator int() const {
return someData;
}
template<typename EnumType2, typename>
friend class EnumArray;
};
void testfunc() {
EnumType myEnumIdx;
// does not compile
std::vector<int> vec1(10);
// error: ‘EnumType::operator int()’ is private
// vec1[myEnumIdx] = 1;
// does compile cause EnumArray is a friend of EnumType and can array private implicit conversion operator to int
EnumArray<EnumType, int> arr;
arr[myEnumIdx] = 1;
EnumType2 myEnumIdx2;
// does not compile
// error: no match for ‘operator[]’ (operand types are ‘EnumArray’ and ‘EnumType2’)
// note: no known conversion for argument 1 from ‘EnumType2’ to ‘const EnumType&’
arr[myEnumIdx2] = 1;
}