Reputation: 5460
Argument dependent lookup says:
For arguments of class type (including union), the set consists of... a) The class itself b)...
Then why can't printX find X?
#include<iostream>
using namespace std;
class A {
public:
static const int X = 1;
};
class B {
public:
static void printX(A a)
{
cout << "X is " << X << endl;
}
};
int main(int argc, char** argv)
{
A a;
B::printX(a);
return 0;
}
Upvotes: 3
Views: 84
Reputation: 206727
I want to expand on the answer by @Nawaz that throws some light on the meaning of "the set consists of... a) The class itself".
An example program:
#include <iostream>
void bar(int ) { std::cout << "Came to ::bar(int)\n"; }
namespace foo
{
struct A2;
struct A1
{
friend void bar(A1 const&) { std::cout << "Came to foo::bar(A1 const&)\n"; }
friend void bar(A2 const&) { std::cout << "Came to foo::bar(A2 const&)\n"; }
};
struct A2
{
};
}
struct B
{
friend void bar(B) { std::cout << "Came to ::bar(B)\n"; }
};
int main()
{
foo::A1 a1;
foo::A2 a2;
B b;
int i = 0;
bar(i); // This resolves to the only bar() in the global namespace.
bar(a1); // This resolves to the appropriate overloaded friend function
// defined in foo::A1 because the scopes for looking up the
// function includes class foo::A1
bar(a2); // Error. The search for bar include foo::A2 but not foo::A1.
bar(b); // This resolves to the friend function defined in B because
// the scopes for looking up the function includes class B
}
Upvotes: 1
Reputation: 361772
That is not what ADL is supposed to do. ADL works for unqualified function call, and the function is first searched in the namespace(s) in which the type(s) of the argument(s) is/are defined.
Example,
namespace N
{
struct A {};
void f(A const &) {}
}
N::A a;
N::f(a); //qualified function call. ADL is not needed.
f(a); //unqualified function call. ADL works here
In the above example f(a)
calls f()
from the namespace N
. Since f(a)
is unqualified function call, ADL enables the compiler to first search the function f
in the namespace N
as the type of the argument a
is defined in N
.
Hope that helps.
Upvotes: 5