0

code:

namespace asd {
    class A { };
    void f(A &a) { }
}

void f(asd::A &a) { }

int main() {
    asd::A instance;
    f(instance);
    return 0;
}

error:

D:\>g++ -Wall -std=c++98 -pedantic a.cpp
a.cpp: In function 'int main()':
a.cpp:10:12: error: call of overloaded 'f(asd::A&)' is ambiguous
a.cpp:10:12: note: candidates are:
a.cpp:6:6: note: void f(asd::A&)
a.cpp:3:7: note: void asd::f(asd::A&)

why does the compiler search the function 'f' in namespace asd's scope?
why is this called overloading? this is two different functions.
i would understand the error if the main funcion was like this:

int main() {
    using asd::f;
    asd::A instance;
    f(instance);
    return 0;
}

and i would get an error... but with this i dont...

this situation is same as when i do this?

std::cout << str;
// meaning 1:
std::operator<<(std::cout, str);
// meaning 2:
::operator<<(std::cout, str);

3 Answers3

1

When you do

using asd::f;

you tell the compiler "when I use the symbol f in the current scope, I actually mean asd::f". That's why it works.

As for the first case, it's because the compiler looks in the scope of the type of instance (that is asd) as well as the global scope. It's called Argument Dependent Lookup.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

C++ does an argument dependent lookup. This means if you have an argument of a particular class type for a function, then to find the function the compiler will lookup function name in the namespace containing the argument's type.

In the following code, you have specified instance as variable of class A which is namespace asd

int main() {
    asd::A instance;
    f(instance);
    return 0;
}

Hence it will lookup for f in the asd namespace as well. To resolve this use: ::f(instance); for calling f in global namespace or asd::f(instance); in asd namespace.

This is called koenig lookup. Go to this link, if you want to understand more.

benipalj
  • 704
  • 5
  • 9
1

why does the compiler search the function 'f' in namespace asd's scope?

Argument-dependent lookup. The argument type A is scoped in asd, so that namespace is also searched for suitable overloads.

why is this called overloading? this is two different functions.

That's exactly what overloading means: two functions with the same name but in different scopes, or taking different parameters.

this situation is same as when i do this?

Yes, it could mean either; but since there is no ::operator<<, there is no ambiguity.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644