gpt4 book ai didi

c++ - 未命名和命名命名空间解析

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:39:12 24 4
gpt4 key购买 nike

对同时存在于未命名空间和本地命名空间中的名称的引用是否应该导致歧义错误或解析是否明确定义?我看到以下在 G++ 和 Clang 上运行良好,在 MSVC 上运行不佳。

namespace Foo
{
class Bar
{
public:
int x;
};
}

namespace
{
class Bar
{
public:
int y;
};
}

namespace Foo
{

void tester()
{
Bar b;
}

}

int main()
{
Foo::tester();
return 0;
}

最佳答案

GCC 和 Clang 是对的。在 Foo::tester 中,Bar 的非限定使用明确指代 Foo::Bar

非限定查找由 C++11 3.4.1/1 指定:

the scopes are searched for a declaration in the order listed in each of the respective categories; name lookup ends as soon as a declaration is found for the name.

搜索在函数中使用名称的范围在 3.4.1/6 中列出:

A name used in the definition of a function [...] that is a member of namespace N [...] shall be declared before its use in the block [...] or, shall be declared before its use in namespace N or, if N is a nested namespace, shall be declared before its use in one of N’s enclosing namespaces.

在这种情况下,函数是 Foo 的成员,因此 Foo 在封闭(全局)命名空间之前被搜索,其中包括未命名的命名空间。 Foo::Bar 在那里找到,查找结束。

关于c++ - 未命名和命名命名空间解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26850784/

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