Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which look up rule prevents the compiler from finding the function?

Tags:

c++

void Foo(int i)
{
}
struct Bar
{
    static void Foo() { Foo(1); }
};

The above code does not compile. It cannot find Foo(int). Why? I know it has to do with having the same function name, but did not get further understanding the problem.

Why do I need a qualified lookup?

like image 453
lars Avatar asked May 10 '17 10:05

lars


2 Answers

From 3.4.1 (emphasis mine)

In all the cases listed in 3.4.1, the scopes are searched for a declaration in the order listed in each of the respective categories; name lookup ends as soon as a declaration is found for the name. If no declaration is found, the program is ill-formed.

In this particular case the first scope to be searched is the function local scope. Foo is not found there. Then comes the class scope. Since the name Foo is found in it, the name lookup stops there and the other Foo does not participate in overload resolution at all.

like image 156
Armen Tsirunyan Avatar answered Oct 02 '22 23:10

Armen Tsirunyan


If a function in a particular namespace shares the same name as one in a global namespace, then the one in the global namespace is not found.

Unfortunately the C++ standard does not allow you to bring in the global namespace into the current one with an appropriate using statement, although you can use using ::Foo; to pull in that particular function:

void Foo(char)
{
}

struct Bar
{
    static void Foo(double) { }
    static void Foo() {
        using ::Foo;
        Foo('c'); // correct overload is found since ::Foo is pulled into scope
        Foo(3.0);
    }
};

Otherwise you need to use the scope resolution operator to find the global function:

struct Bar
{
    static void Foo() { ::Foo(1); }
};
like image 39
4 revs, 2 users 80% Avatar answered Oct 02 '22 22:10

4 revs, 2 users 80%