Equivalent of "using namespace X" for scoped enumerations?
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.
So the short answer is no, but fortunately this is going to change in a recently finalized feature set of C++20. According to this accepted proposal you will be able to do the following:
enum class CatState
{
sleeping,
napping,
resting
};
std::string getPurr(CatState state)
{
switch (state)
{
using enum CatState;
// our states are accessible without the scope operator from now on
case sleeping: return {}; // instead of "case CatState::sleeping:"
case napping: return "purr";
case resting: return "purrrrrr";
}
}