Let's say I have an array of integers, one for each member of a particular enum class. I can cast the enum class to an int to index the array but I'd rather use the enum class for type safety since that's the only type that should be allowed, in my case, to index that array.
- Is there a way to do this without overloading the [] operator?
- If I overload the operator there will be an extra function call cost, correct?
CodePudding user response:
If you are talking about a raw c-style-array, then there is little chance of forcing the index type to be an enum class. However, your assumption in point 2. is not necessarily true. If you inline define the function along with its declaration chances are high that for a trivial wrapper function the compiler will optimise the call:
enum class E {/*...*/};
template <typename T, std::size_t N>
struct A {
T data[N];
auto& operator[](E e) {
return data[static_cast<std::size_t>(e)];
}
auto const& operator[](E e) const {
return data[static_cast<std::size_t>(e)];
}
};
The calls to these inline functions are removed by the compiler. (live demo)
CodePudding user response:
Yes, there is a way to do this without overloading the [] operator. One way to achieve this is to use a std::map that maps from the enum class to the corresponding integer index. This allows you to use the enum class directly as the key for the map, without having to cast it to an integer.
Here is an example:
enum class MyEnum {
VALUE_1,
VALUE_2,
VALUE_3
};
std::map<MyEnum, int> my_map;
// initialize the map
my_map[MyEnum::VALUE_1] = 0;
my_map[MyEnum::VALUE_2] = 1;
my_map[MyEnum::VALUE_3] = 2;
// use the map to get the index for a particular value of the enum class
int index = my_map[MyEnum::VALUE_1];
Using a std::map in this way does not add any extra function call overhead compared to using an array, since the std::map class uses a hash table internally to provide constant-time lookup of the index for a given enum value.