Enum class as an array index

I did the listing as:

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 }; 

and then I will try to define the array as I typed below, but I got an error, size of array 'KEY_PRESS_SURFACES' has non-integral type 'KeyPressSurfaces'

 SDL_Surface*KEY_PRESS_SURFACES[KeyPressSurfaces::KEY_PRESS_SURFACE_TOTAL]; 

I understand that the error is fine, but I don’t know where to move KeyPressSurfaces to determine the constant in the enumeration.

I also understand that I can just use enum and not enum class , but it seems to me that this should work, and I want to learn how to do it.

Any answer / advice is welcome! Thanks!

+6
source share
4 answers

The enum scope ( enum class ) is implicitly converted to integers. You need to use static_cast :

 SDL_Surface*KEY_PRESS_SURFACES[static_cast<int>(KeyPressSurfaces::KEY_PRESS_SURFACE_TOTAL)]; 
+9
source

You can convert enum to int using the template function and you will get more readable code:

 #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; } 

I fount to_underlying function here

+7
source

Remove the class keyword or explicitly pass it to the integral type.

+1
source

Alternatively, you can replace array with map , which also means that you can get rid of KEY_PRESS_SURFACE_TOTAL :

 enum class KeyPressSurfaces { KEY_PRESS_SURFACE_DEFAULT, KEY_PRESS_SURFACE_UP, KEY_PRESS_SURFACE_DOWN, KEY_PRESS_SURFACE_LEFT, KEY_PRESS_SURFACE_RIGHT }; std::map<KeyPressSurfaces, SDL_Surface*> KEY_PRESS_SURFACES; 
-2
source

All Articles