c++ - 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++。
我的意思是你可以这样做:
namespace foo {
enum value {
a,b,c,count
};
}
那么 to int 转换是隐式的,并且您不会污染包含的命名空间。
这里的解决方案非常接近 0 开销,并允许您使用枚举(并且仅枚举)作为[]
.
所以你得到:
enum_array<foo, T> arr;
并arr
表现得像你想要的那样。
推荐阅读
- browser - 如何在单个图像中从浏览器截取整个网页的屏幕截图
- javascript - Angular @input 属性以感叹号结尾?
- php - 从数据库中选择数据,连接它们,写入文件并剪切
- javascript - 条件渲染时避免在组件内部调用效果
- css - css关键帧动画未在浏览器上显示
- javascript - 在 EJS 模板中获取表单参数
- c# - 如何将模式过滤器添加到一个 Swashbuckle api 文档版本
- javascript - 将数字拆分为数组的方法
- docker - Anchore CLI 卡在“not_analyzing”和其他问题上
- java - 如何始终为 ResponseEntity 返回 JSON 对象(不是数组)
>?