gpt4 book ai didi

c++ - 在 typedef 中使用相同的名称并从命名空间中使用

转载 作者:太空狗 更新时间:2023-10-29 21:10:04 26 4
gpt4 key购买 nike

示例代码:

struct X { void f() {} };
typedef X A;

namespace N {
struct A { void g() {} };
};

using N::A;

int main()
{
A a;
a.f();
}

此代码编译正确,A a; 创建一个 X,而不是 N::A

标准中的哪条规则涵盖了这种行为?我原以为 A a; 会产生歧义。如果我将第一个结构命名为 A 而不是 X 并删除 typedef,那么我确实会收到这样的错误。 (g++ 8.3)

最佳答案

根据 [namespace.udecl]/1 using N::A 将未限定的 A 引入出现 using 声明的声明区域。

... the unqualified-id is declared in the declarative region in which the using-declaration appears as a synonym for each declaration introduced by the using-declarator.

所以歧义由[namespace.udecl]/13共同覆盖

Since a using-declaration is a declaration, the restrictions on declarations of the same name in the same declarative region also apply to using-declarations.

[basic.scope.declarative]/4

Given a set of declarations in a single declarative region, each of which specifies the same unqualified name,

  • they shall all refer to the same entity, or all refer to functions and function templates; or
  • exactly one declaration shall declare a class name or enumeration name that is not a typedef name and the other declarations shall all refer to the same variable, non-static data member, or enumerator, or all refer to functions and function templates; in this case the class name or enumeration name is hidden.

OP 中的 typedef 声明和 using 声明都没有填写任何一个项目符号,因此同一声明区域中的这对声明格式错误。

关于c++ - 在 typedef 中使用相同的名称并从命名空间中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55896837/

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