假设我们有一个enum
类型foo
,我们想用它来索引静态大小arr
数组。
如果我们想为此使用enum class
,我们可以像这样尝试:
enum class foo
{
a,
b,
c,
count
};
std::array<T, static_cast<int>(foo::count)> arr;
但是,count
字段是一个黑客。我们能以更优雅的方式获得foo
字段的数量吗?
无论如何,真正糟糕的是我们还需要使用static_cast
访问数组:arr[static_cast<int>(foo::a)]
。
当然,我们可以编写一个自定义的"at"函数(见 https://www.fluentcpp.com/2019/01/15/indexing-data-structures-with-c-scoped-enums/(或提供一个"enum_array"类(见 https://stackoverflow.com/a/55259936/547231(,但这两种解决方案都有些复杂,我们最好放弃并使用一个简单的std::array<T, int>
代替......
但是,阅读arr[foo::a]
比arr[0]
更直观,我们始终需要记住后者中索引0
的含义。
我们能做得更好吗?
不,不是真的。
有许多建议可以对枚举值进行静态反射。 目前还没有C++。
我的意思是你可以做到:
namespace foo {
enum value {
a,b,c,count
};
}
那么 to int 转换是隐式的,并且不会污染包含的命名空间。
这里的解决方案非常接近 0 开销,允许您使用枚举(并且仅枚举(作为[]
键。
所以你得到:
enum_array<foo, T> arr;
arr
的行为就像你想要的那样。
作为部分解决方案,您可以定义
constexpr std::underlying_type_t<foo> operator*(foo f) {
return static_cast<std::underlying_type_t<foo>>(f);
}
然后写
int bar(std::array<int, *foo::count>& arr) {
return arr[*foo::b];
}
演示