gpt4 book ai didi

c++ - 如何在没有显式强制转换的情况下将 C++ 枚举类枚举器用作 std::array 索引

转载 作者:搜寻专家 更新时间:2023-10-31 00:53:40 25 4
gpt4 key购买 nike

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

我还为固定大小的 std::array 使用了 typedef

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。我该怎么做?

最佳答案

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

这是一个例子。

您可以这样定义 enum_array:

#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++ - 如何在没有显式强制转换的情况下将 C++ 枚举类枚举器用作 std::array 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47972453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com