问题
In this answer it was mentioned that in the upcoming C++20 standard it is possible to use the using
statement on enum class
and import the enum fields into the local namespace.
I was wondering if that also means that I can also use it within class definitions like this:
class Foo {
enum class Color
{
red,
blue
};
using enum Color;
};
int main()
{
Foo::Color c = Foo::red;
}
Or do I still need to give the full namespace?:
Foo::Color c = Foo::Color::red;
I tried it in wandbox.org, but it seems that neither gcc nor clang know about using enum
yet.
回答1:
Yes, Foo::Red
will work fine. using enum E
behaves as, from [enum.udecl]:
A using-enum-declaration introduces the enumerator names of the named enumeration as if by a using-declaration for each enumerator.
And the standard contains an example of exactly this case:
[ Note: A using-enum-declaration in class scope adds the enumerators of the named enumeration as members to the scope. This means they are accessible for member lookup. [ Example:
enum class fruit { orange, apple }; struct S { using enum fruit; // OK, introduces orange and apple into S }; void f() { S s; s.orange; // OK, names fruit::orange S::orange; // OK, names fruit::orange }
— end example ] — end note ]
Note however that there is some controversy around the particular spelling for this feature. enum E
is what's known as an elaborated type specifier (much like class C
or struct S
). Typically, elaborated type specifiers behave exactly the same was as their underlying versions. Elaborating is just meant to disambiguate, and you rarely need to disambiguate, so you wouldn't see it very often. However, in this particular case, using enum E
and using E
actually mean wildly different and wholly unrelated things. So keep in mind that there is a chance that this feature may not yet actually make C++20, despite currently being in the working draft and even having been published in the CD. As such, it's unlikely that compilers will implement this feature until they're sure it's necessary to implement (C++20 isn't exactly lacking in work for compiler writers...)
来源:https://stackoverflow.com/questions/57913492/use-using-enum-in-c20-in-classes-possible