gpt4 book ai didi

c++ - 找不到全局命名空间范围内的函数名称

转载 作者:行者123 更新时间:2023-11-30 05:24:22 27 4
gpt4 key购买 nike

根据 unqualified lookup in cppreference.com :

For a name used in the definition of a function, either in its body or as part of default argument, where the function is a member of user-declared or global namespace, the block in which the name is used is searched before the use of the name, then the enclosing block is searched before the start of that block, etc, until reaching the block that is the function body. Then the namespace in which the function is declared is searched until the definition (not necessarily the declaration) of the function that uses the name, then the enclosing namespaces, etc.

所以我认为在全局命名空间范围内定义的函数名应该通过非限定查找简单地找到。但是,以下代码无法编译:

#include <iterator>
#include <iostream>

namespace AA{
class AAA{};
};

using namespace AA;

int begin(AAA ){
return 3;
}

int main(){
using std::begin; // to add std::begin in the name candidate set

auto x = AAA();
return begin(x); // compile error, ::begin cannot be found
}

GCC(6.1.1) 和 Clang(3.8.0) 报告相同的 error .

而且,无论是删除 using std::begin 语句还是将 class AAA 移至 namespace AA,上述程序都能成功编译。所以我认为一旦通过名称查找找到我的begin,就会通过重载解析来选择它。因此问题是:为什么在上面的代码案例中根本找不到我在全局范围内声明和定义的 begin 函数?

最佳答案

请注意 unqualified name lookup如果找到名称(在某些范围内),将停止,然后将不会搜索更多范围。对于您的示例代码,名称 begin 将在 main() 的函数范围内找到,(指的是 std::begin) ,然后停止名称查找,因此不会检查全局范围内的名称。

..., name lookup examines the scopes as described below, until it finds at least one declaration of any kind, at which time the lookup stops and no further scopes are examined.

来自您发布的引文(强调由我添加):

etc, until reaching the block that is the function body. (the name lookup will stop here, i.e. in the block of main() function body)

Then the namespace ... (The further namespace won't be searched.)

关于c++ - 找不到全局命名空间范围内的函数名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38690369/

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