gpt4 book ai didi

c++ - 可以在类中使用 C++20 中的 'using enum' 吗?

转载 作者:行者123 更新时间:2023-12-02 01:50:31 27 4
gpt4 key购买 nike

this answer有人提到,在即将推出的 C++20 标准中,可以在 enum class 上使用 using 语句,并将枚举字段导入本地命名空间。

我想知道这是否也意味着我也可以在类定义中使用它,如下所示:

class Foo {
enum class Color
{
red,
blue
};
using enum Color;
};

int main()
{
Foo::Color c = Foo::red;
}

或者我还需要提供完整的命名空间吗?:

    Foo::Color c = Foo::Color::red;

我在 wandbox.org 上尝试过,但似乎 gcc 和 clang 都不知道使用 enum

最佳答案

是的,Foo::Red 可以正常工作。 使用 enum E 的行为类似于 [enum.udecl] :

A using-enum-declaration introduces the enumerator names of the named enumeration as if by a using-declaration for each enumerator.

并且该标准包含一个正是这种情况的示例:

[ 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 ]

<小时/>

但请注意,围绕此功能的特定拼写存在一些争议。 enum E 是所谓的详细类型说明符(很像 class Cstruct S)。通常,详细的类型说明符的行为与其底层版本完全相同。阐述只是为了消除歧义,而你很少需要消除歧义,所以你不会经常看到它。然而,在这种特殊情况下,using enum Eusing E 实际上意味着截然不同且完全不相关的事物。因此请记住,尽管此功能目前处于工作草案中,甚至已经在 CD 中发布,但它可能尚未真正成为 C++20。因此,编译器不太可能实现此功能,除非他们确定有必要实现(C++20 并不完全缺乏编译器编写者的工作...)

关于c++ - 可以在类中使用 C++20 中的 'using enum' 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57913492/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com