Function names in global namepsace scope cannot be found

你。 提交于 2019-12-24 06:43:54

问题


According to 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.

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
}

Both GCC(6.1.1) and Clang(3.8.0) reports the same error.

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?


回答1:


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):

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.)



来源:https://stackoverflow.com/questions/38690369/function-names-in-global-namepsace-scope-cannot-be-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!