lundi 25 décembre 2017

How to use a C++ enum class enumerator as std::array index without an explicit cast

I want to use a C++ enum class as std:array index without calling an explicit cast, when I want to refer to a specific index.

I furthermore use a typedef for a fixed sized std::array.

typedef std::array<int, 3> MyType;
enum class MyEnum {
  ENUMERATOR0 = 0,
  ENUMERATOR1 = 1,
  ENUMERATOR2 = 2,
};

So instead of using:

MyType my_type = {0};
my_type[static_cast<int>(MyEnum::ENUMERATOR0)] = 42;

I want to use:

my_type[MyEnum::ENUMERATOR0] = 42;

Therefore, I assume it is required to overload the subscript operator of my MyType (std::array) type. However, I couldn't figure out, how to overload the subscript operator in my case. For simplicity reasons, I would like to avoid using a class instead of the typedef. How can I do this?

Aucun commentaire:

Enregistrer un commentaire