枚举类作为数组索引

Hay*_*per 13 c++ arrays enums sdl

我做了一个枚举:

enum class KeyPressSurfaces {
    KEY_PRESS_SURFACE_DEFAULT,
    KEY_PRESS_SURFACE_UP,
    KEY_PRESS_SURFACE_DOWN,
    KEY_PRESS_SURFACE_LEFT,
    KEY_PRESS_SURFACE_RIGHT,
    KEY_PRESS_SURFACE_TOTAL
};
Run Code Online (Sandbox Code Playgroud)

然后我尝试在下面输入时定义一个数组,但是我收到了错误, size of array 'KEY_PRESS_SURFACES' has non-integral type 'KeyPressSurfaces'

SDL_Surface*KEY_PRESS_SURFACES[KeyPressSurfaces::KEY_PRESS_SURFACE_TOTAL];
Run Code Online (Sandbox Code Playgroud)

我理解错误很好,但我不知道在KeyPressSurfaces枚举中移动限定常量的位置.

我也意识到我可以使用一个enum而不是一个enum class,但我觉得这应该有用,我想学习如何做到这一点.

任何回应/建议表示赞赏!谢谢!

Sim*_*ple 13

Scoped enums(enum class)不能隐式转换为整数.你需要使用static_cast:

SDL_Surface*KEY_PRESS_SURFACES[static_cast<int>(KeyPressSurfaces::KEY_PRESS_SURFACE_TOTAL)];
Run Code Online (Sandbox Code Playgroud)

  • 这是正确的,但这也很丑陋,因为这些小事加起来让 c++ 现在变得不受欢迎 (9认同)

gom*_*ons 11

您可以将您转换enumint使用模板功能,您将获得更可读的代码:

#include <iostream>
#include <string>
#include <typeinfo>

using namespace std;

enum class KeyPressSurfaces: int {
    KEY_PRESS_SURFACE_DEFAULT,
    KEY_PRESS_SURFACE_UP,
    KEY_PRESS_SURFACE_DOWN,
    KEY_PRESS_SURFACE_LEFT,
    KEY_PRESS_SURFACE_RIGHT,
    KEY_PRESS_SURFACE_TOTAL
};

template <typename E>
constexpr typename std::underlying_type<E>::type to_underlying(E e) {
    return static_cast<typename std::underlying_type<E>::type>(e);
}


int main() {
    KeyPressSurfaces val = KeyPressSurfaces::KEY_PRESS_SURFACE_UP;
    int valInt = to_underlying(val);
    std::cout << valInt << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这里有to_underlying功能


Ste*_*fan 6

您可以对数组进行操作:

/** \brief It's either this or removing the "class" from "enum class" */
template <class T, std::size_t N>
struct EnumClassArray : std::array<T, N>
{
    template <typename I>
    T& operator[](const I& i) { return std::array<T, N>::operator[](static_cast<std::underlying_type<I>::type>(i)); }
    template <typename I>
    const T& operator[](const I& i) const { return std::array<T, N>::operator[](static_cast<std::underlying_type<I>::type>(i)); }
};
Run Code Online (Sandbox Code Playgroud)


kni*_*vil 5

删除class关键字或显式转换为整数类型。