I have an enum type in my code, like this:
enum class GameConsts: size_t { NUM_GHOSTS = 4 };
I find myself repeating the required static_cast to get the enum value:
Ghost ghosts[static_cast<size_t>(GameConsts::NUM_GHOSTS)];
// and...
for(size_t i = 0; i < static_cast<size_t>(GameConsts::NUM_GHOSTS); ++i) { ... }
What is the best way to avoid this repetitive static_cast?
The option of allowing implementation of a casting operator was raised in this ISO proposal discussion, but seems to drop.
Related SO question: Overloading cast operator for enum class
Davis Herring added in a comment that C++23 added: std::to_underlying which should be the answer when we have C++23 compiler support. But the question is for C++20.
Your first option is to use a
constexprinstead of an enum:You can put it inside a proper context, such as GameConsts struct:
Then there is no need for a casting:
In case you actually need an enum, as you have a list of related values that you want to manage together, then you may use unscoped enum (i.e. drop the
classfrom theenum classand use a regular plain-oldenum) but put it inside a struct to preserve the context. I will use here an example of another enum, managing several related values.The repeated use of
static_castmay happen for the above enum, in a switch-case like that:To avoid the repeated need for
static_castyou may go with:Option 1: Use simple unscoped enum inside a struct
And since old-style enum can cast implicitly to its underlying type, you can get away of the casting:
Option 2: Add your own conversion function
If you actually prefer, or have to use
enum classyou may have a simple conversion function for which the copy-paste is just calling the function, being less cumbersome than the fullstatic_castsyntax:And:
If you choose the last option, you may want to generalize it for any type of
enum, with this code:Option 3: Cast to the enum and not from the enum
As suggested by @Nathan Pierson and @apple apple in the comments, the casting can be to the enum, with this code:
This should work fine even if
key_pressedis not any of the enum values, as we have a fixed enum (having a stated underlying type, note that an enum class is always fixed, even if not stated explicitly). See also: What happens if you static_cast invalid value to enum class?