Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is usual unqualified lookup for the function name differs from lookup for variable name?

Consider the following code:

#include <iostream>

int a=5;//1
extern int a;//2

int main(){ cout << a; }

During unqualified name lookup declaration#1 will be found and unqualified name lookup ends just after #1 is found.

But consider another example:

#include <iostream>

void foo() { cout << "zero arg"; }
void foo(int a) { cout << "one arg"; }

int main(){ foo(4); }

In that case void foo();'s definition will be found first. But unqualified name lookup doesn't end. Why? Where is it specified in the standard? In general, I'm interested in:

When does unqualified name lookup ends for the postfix-expression for the function call?

Note: I know what does ADL mean. The set of declarations produced by ADL is empty in that case.

UPD:

But if we write the following:

int foo(int a) { return 0; }
namespace A
{
    int foo() { return 1; }
    int a= foo(5); //Error: to many arguments
}

This implies that enclosing namespace does not considering. I would like to know where is it specified too.

like image 286
St.Antario Avatar asked May 31 '14 05:05

St.Antario


1 Answers

In that case void foo();'s definition will be found first. But unqualified name lookup doesn't end. Why?

Because standard says:

Name lookup may associate more than one declaration with a name if it finds the name to be a function name; the declarations are said to form a set of overloaded functions (13.1). Overload resolution (13.3) takes place after name lookup has succeeded.

So in case of function, name lookup does not end after finding first match, it collects all the names, and then overload resolution occurs.

Update

For the updated question, you are back to your previous question

name lookup ends as soon as a declaration is found for the name.

So as soon as foo is found in inner scope, no further search is conducted.

But if you use namespace qualified name, then the specified namespace will be searched:

int a = ::foo(5); // finds foo in global namespace.

So in general, for unqualified search, first search is conducted in the current scope, if not found then next enclosing scope and so forth. However, as soon as a name is found, search ends, it does not matter if the name is usable or not. It means, for function, it may not be the correct one, may be there is an overloaded one in enclosing scope which is correct, but search does not continue to that.

like image 154
Rakib Avatar answered Sep 28 '22 06:09

Rakib