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.
Not before C++20. Just as there’s no equivalent for having to type
ClassName::for static class members. You can’t sayusing typename ClassNameand then get at the internals. The same goes for strongly typedenums.C++20 adds the
using enum Xsyntax, which does what it looks like.You can of course not use
enum classsyntax, just using regularenums. 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.