I have taken following example from here.
namespace NS
{
class A {};
void f( A *&, int ) {}
}
int main()
{
NS::A *a;
f( a, 0 ); //calls NS::f
}
I came across this like, while I was trying to find extension functions in C++.
Does above example simply means, that if I call any function with first argument as object of any class, and if that function does not found in current namespace, then compiler find out for required function in first objects` namespace?
If I am wrong, this question seems to be unrelated, but does extension method in C# have any relationship with ADL?
You asked:
Does above example simply means, that if I call any function with first argument as object of any class, and if that function does not found in current namespace, then compiler find out for required function in first objects` namespace?
Answer:
By using ADL, the compiler will find all functions that are potential candidates. It finds exactly one, it will use it. If it finds more than one, it will error out. It does not use ADL only if cannot find a function in the current namespace.
Example 1:
#include <iostream>
using namespace std;
namespace NS1
{
struct A {};
int foo(A a) { return 10; }
}
namespace NS2
{
struct A {};
int foo(A a) { return 20; }
}
int main()
{
cout << foo(NS1::A()) << endl; // Resolves to NS1::foo by using ADL
cout << foo(NS2::A()) << endl; // Resolves to NS2::foo by using ADL
}
Example 2:
#include <iostream>
using namespace std;
namespace NS1
{
struct A {};
}
int foo(NS1::A a) { return 10; }
namespace NS2
{
struct A {};
int foo(A a) { return 20; }
}
int foo(NS2::A a) { return 30; }
int main()
{
cout << foo(NS1::A()) << endl; // Resolves to ::foo(NS1::A)
cout << foo(NS2::A()) << endl; // Unable to resolve.
// ::foo(NS2::A) and NS2::foo(NS2::A) are
// equally valid candidates.
}