the*_*mer 3 c++ enums enum-class c++20
在此答案中,提到了在即将到来的C ++ 20标准中可以使用usingon语句,enum class并将枚举字段导入本地名称空间。
我想知道这是否还意味着我也可以在这样的类定义中使用它:
class Foo {
enum class Color
{
red,
blue
};
using enum Color;
};
int main()
{
Foo::Color c = Foo::red;
}
Run Code Online (Sandbox Code Playgroud)
还是我仍然需要提供完整的名称空间?:
Foo::Color c = Foo::Color::red;
Run Code Online (Sandbox Code Playgroud)
我在wandbox.org中尝试过,但似乎gcc和clang都不知道using enum。
是的,Foo::Red可以正常工作。using enum E从[enum.udecl]表现为:
一个使用-枚举声明似乎通过推出名为枚举的枚举名称使用声明的每个枚举。
该标准包含了这种情况的示例:
[注意:类范围中的using-enum-declaration将命名枚举的枚举数添加为范围的成员。这意味着它们可用于成员查找。[示例:
Run Code Online (Sandbox Code Playgroud)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 }—结束示例 ] —结束注释]
但是请注意,此功能的特定拼写存在一些争议。enum E是所谓的精细类型说明符(很像class C或struct S)。通常,精心设计的类型说明符的行为与其基本版本完全相同。详细说明只是为了消除歧义,您几乎不需要消除歧义,因此您不会经常看到它。然而,在这种特殊情况下,using enum E和using E实际上是指完全不同且完全不相关的事物。因此请记住,尽管当前正在起草工作中,甚至已经发布在CD中,但该功能仍有可能无法真正实现C ++ 20。因此,除非编译器确定有必要实施,否则不太可能会实现此功能(对于编译器作者来说,C ++ 20确实不缺乏工作...)