I am using a scoped enum to enumerate states in some state machine that I'm implementing. For example, let's say something like:
enum class CatState { sleeping, napping, resting };
In my cpp file where I define a state transition table, I would like to use something equivalent to using namespace X
so that I don't need to prefix all my state names with CatState::
. In other words, I'd like to use sleeping
instead of CatState::sleeping
. My transition table has quite a few columns, so avoiding the CatState::
prefix would keep things more compact and readable.
So, is there a way to avoid having to type CatState::
all the time?
Yeah, yeah, I'm already aware of the pitfalls of using namespace
. If there's an equivalent for strongly-typed enums, I promise to only use it inside a limited scope in my cpp implementation file, and not for evil.
A scoped enum looks exactly as a traditional enum except that the keyword class (or struct – the two keywords are interchangeable in this context) appears between the keyword enum and the enum name, as shown in the following example: enum class Color //C++11 scoped enum.
Enum, which is also known as enumeration, is a user-defined data type that enables you to create a new data type that has a fixed range of possible values, and the variable can select one value from the set of values.
So, is there a way to avoid having to type
CatState::
all the time?
Not before C++20. Just as there's no equivalent for having to type ClassName::
for static class members. You can't say using typename ClassName
and then get at the internals. The same goes for strongly typed enum
s.
C++20 adds the using enum X
syntax, which does what it looks like.
You can of course not use enum class
syntax, just using regular enum
s. But then you lose strong typing.
It should be noted that one of the reasons for using ALL_CAPS for weakly typed enums was to avoid name conflicts. Once we have full scoping and strong typing, the name of an enum is uniquely identified and cannot conflict with other names. Being able to bring those names into namespace scope would reintroduce this problem. So you would likely want to use ALL_CAPS again to help disambiguate the names.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With