Doesn't ADL looks up static member functions?

a 夏天 提交于 2019-12-21 11:21:33

问题


This is follow up question from Does argument dependent lookup only search namespaces or classes too? , In which @David Rodríguez said "ADL will look in the enclosing namespace of the type, and also inside the type itself" . I may have got him wrong what he tried to say but I was trying this example:

struct foo{
    static void bar(foo* z){}    
};

int main(){
    foo* z;
    bar(z);
}

It doesn't compiles, producing the error " ‘bar’ was not declared in this scope " . Is it the case that ADL doesn't considers the static member function?. I mean in the example associated class is foo so wouldn't ADL look inside the class? . Can anyone please simplify the rules here?


回答1:


He probably meant this:

struct foo{
    friend void bar(foo* z){}    //not static, its friend now
};

foo* z;
bar(z); //fine now

But then technically bar() is not inside foo. It is still in the enclosing namespace of foo.

--

EDIT:

He indeed meant friend, as he said (emphasis mine):

The best example is a friend function that is defined inside the type

And his example illustrates further. Probably you need to read "defined inside", rather than only "inside".

The word "defined" is all that makes the difference, because it looks like the function's name bar is introduced into the scope of the class, but in actuality, the name bar is introduced into the enclosing namespace of foo (see §3.3.1/3-4 and §11.3/6).

Here is a better example:

namespace Demo
{
     struct foo
     {
       friend void bar(foo* z){}
     };
}

foo *z;
bar(z); //foo (type of z) is inside Demo, so is bar
        //(even though bar is defined inside foo!)

bar(NULL);    //error - NULL doesn't help ADL.
bar(nullptr); //error - nullptr doesn't help ADL.

bar(static<foo*>(NULL)); //ok - ADL

Note that the name bar, even though is introduced into the namespace Demo, is hidden, and thus cannot be used from outside using usual name-lookup:

using namespace Demo; //brings ALL (visible) names from Demo to current scope

bar(NULL); //STILL error - means bar is invisible

Or,

Demo::bar(NULL);       //error - not found
Demo::foo::bar(NULL);  //error - not found

Hope that helps.



来源:https://stackoverflow.com/questions/14725214/doesnt-adl-looks-up-static-member-functions

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