首页 > 解决方案 > How should we use an enum class for indexing (or should we better avoid this)?

问题描述

Say we have an enum type foo which we want to use to index an array arr of static size.

If we want to use an enum class for this, we could try it like this:

enum class foo
{
    a,
    b,
    c,
    count
};

std::array<T, static_cast<int>(foo::count)> arr;

However, the count field is a hack. Can we obtain the number of fields of foo in a more elegant way?

In any case, what's really bad is that we need to access the array using a static_cast as well: arr[static_cast<int>(foo::a)].

Of course we could write a custom "at" function (see https://www.fluentcpp.com/2019/01/15/indexing-data-structures-with-c-scoped-enums/) or provide an "enum_array" class (see https://stackoverflow.com/a/55259936/547231), but both solutions are somehow complicated and we might better give up and use a simple std::array<T, int> instead ...

However, it's way more intuitive to read arr[foo::a] instead of arr[0], where we always need to remember what's the meaning of the index 0 in the latter.

Can we do better?

标签: c++indexingenumsc++17enum-class

解决方案


不,不是。

有许多提案可以实现枚举值的静态反映。还没有 C++。

我的意思是你可以这样做:

namespace foo {
  enum value {
    a,b,c,count
  };
}

那么 to int 转换是隐式的,并且您不会污染包含的命名空间。

这里的解决方案非常接近 0 开销,并允许您使用枚举(并且仅枚举)作为[].

所以你得到:

enum_array<foo, T> arr;

arr表现得像你想要的那样。


推荐阅读