Search code examples
c++argument-dependent-lookup

Why is Koening lookup not working here?


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;
}

Solution

  • 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
    }