找不到全局namepsace范围中的函数名称 [英] Function names in global namepsace scope cannot be found
问题描述
对于函数定义中使用的名称(在其主体中或作为默认参数的一部分)(如果该函数是用户声明的名称或全局名称空间的成员),请在使用该名称的块之前进行搜索使用该名称,然后在该块开始之前搜索该封闭的块,依此类推,直到到达作为函数体的块为止. 然后搜索声明该函数的名称空间,直到使用该名称的函数的定义(不一定是声明),然后是封闭的名称空间等.
因此,我认为在全局名称空间范围中定义的函数名称应仅通过不合理的查找来找到.但是,以下代码无法编译:
So I thought function names defined in global namespace scope shall be found simply through unquailifed lookup. However, the following piece of code fails to compile:
#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)都报告了相同的错误
Both GCC(6.1.1) and Clang(3.8.0) reports the same error.
然后,要么删除using std::begin
语句,要么将class AAA
移到namespace AA
,以上程序成功编译.因此,我认为通过名称查找找到我的begin
后,将通过重载解析来选择它.因此,问题是:为什么在上面的代码案例中根本找不到在全局范围内声明和定义的begin
函数?
And, either I remove the using std::begin
statement or move class AAA
to namespace AA
, the above program compiles successfully. So I think once my begin
is found through name lookup, it will be chosen through overload resolution. Therefore the question is: why my begin
function declared and defined in global scope is simply not found in the code case above?
推荐答案
请注意,不合格的名称如果找到名称(在某个范围内),lookup 将停止,然后将不再搜索其他范围.对于您的示例代码,名称begin
将在main()
的功能范围内找到(指的是std::begin
),然后名称查找停止,因此不会检查全局范围内的名称.>
Note that unqualified name lookup will stop if the name is found (at some scope), then the further scopes won't be searched. For your sample code, the name begin
will be found at the function scope of main()
, (which refers to std::begin
), then name lookup stops, so the name in global scope won't be examined.
...,名称查找按如下所述检查范围,直到找到至少一个任何类型的声明为止,这时查找停止并且不再检查任何范围.
..., 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.
从您发布的报价中(我添加了重点):
From the quotation you posted (emphasis added by me):
等,直到到达作为功能体的块. (名称查找将在此处停止,即在main()函数主体的块中)
然后是名称空间... (不会搜索其他名称空间.)
Then the namespace ... (The further namespace won't be searched.)
这篇关于找不到全局namepsace范围中的函数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!