如何在没有显式强制转换的情况下将C ++枚举类枚举器用作std :: array索引 [英] How to use a C++ enum class enumerator as std::array index without an explicit cast

查看:60
本文介绍了如何在没有显式强制转换的情况下将C ++枚举类枚举器用作std :: array索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我要引用特定索引时,我想使用C ++枚举类作为std:array索引而不调用显式强制转换。

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.

我还使用

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

所以不要使用:

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

我要使用:

my_type[MyEnum::ENUMERATOR0] = 42;

因此,我假设需要重载MyType的下标运算符(std :: array)类型。但是,我不知道该如何重载下标运算符。为了简单起见,我想避免使用类而不是typedef。
我该怎么做?

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?

推荐答案

我找到了一个很好的解决方案。您既可以将枚举类用作数组中的索引,又可以通过子类化std :: array并覆盖其operator []方法来获得确保类型安全(即,防止使用错误的枚举类型作为索引)的额外好处。

I found a good solution for this. You can both use enum classes as indices in your arrays and also get the added benefit of ensuring type safety (i.e. preventing use of the wrong enum type as indices) by subclassing std::array and overriding its operator[] method.

这里是一个例子。

您可以这样定义enum_array:

You can define enum_array like this:

#include <array>

// this is a new kind of array which accepts and requires its indices to be enums
template<typename E, class T, std::size_t N>
class enum_array : public std::array<T, N> {
public:
    T & operator[] (E e) {
        return std::array<T, N>::operator[]((std::size_t)e);
    }

    const T & operator[] (E e) const {
        return std::array<T, N>::operator[]((std::size_t)e);
    }
};

您可以像这样使用它:

int main() {
    enum class Fruit : unsigned int {
        Apple,
        Kiwi
    };

    enum class Vegetable : unsigned int {
        Carrot,
        Potato
    };

    // Old way:
    std::array<int, 3> old_fruits;
    std::array<int, 3> old_veggies;

    old_fruits[(int)Fruit::Apple] = 3;          // compiles but "ugly"
    old_veggies[(int)Vegetable::Potato] = 7;    // compiles but "ugly"

    old_fruits[(int)Vegetable::Potato] = 3;     // compiles but shouldn't compile!
    old_fruits[2] = 6;                          // compiles but may or may not be desirable

    // New way:
    enum_array<Fruit, int, 3> fruits;
    enum_array<Vegetable, int, 3> veggies;

    fruits[Fruit::Apple] = 3;
    veggies[Vegetable::Potato] = 7;

    // fruits[Vegetable::Potato] = 3;   // doesn't compile :)
    // fruits[2] = 6;                   // doesn't compile
    // fruits[(int)Fruit::Apple] = 3;   // doesn't compile
} 

这篇关于如何在没有显式强制转换的情况下将C ++枚举类枚举器用作std :: array索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆