C++ Learning Note(5): Koenig Lookup

cpp

This concept is well explained in the Wikipedia, and also in the codeproject. What confuses me is how this magic mentioned in Wikipedia is played:

While ADL makes it practical for free functions to be part of the interface of a class, it makes namespaces less strict and so can require the use of fully-qualified names when they would not otherwise be needed. For example, the C++ standard library makes extensive use of unqualified calls to std::swap to swap two values.

Here is my lousy approach to mimic the magic:

#include <iostream>
using namespace std;

void g();

void g() { cout << "g is outside NS" << endl; }

namespace NS {
    class A{};
    void f(A) { g(); cout << "f is called" << endl; }
}
int main()
{
    NS::A a;
    f(a);
}

with the following output:

g is outside NS
f is called

It makes sense that the global function is picked by the compiler, which is the only candidate. If we remove the global g Ln 6, and define NS::g before NS::f:

namespace NS {
    class A{};
    void g() { cout << "g is inside NS" << endl; }
    void f(A) { g(); cout << "f is called" << endl; }
}

It compiles, and NS::g is called, so the compiler will pick NS::g if the caller is in NS namespace. Let’s try add a global g back as:

#include <iostream>
using namespace std;

void g() { cout << "g is outside NS" << endl; }

namespace NS {
    class A{};
    void g() { cout << "g is inside NS" << endl; }
    void f(A) { g(); cout << "f is called" << endl; }
}

int main()
{
    NS::A a;
    f(a);
}

The output is:

g is inside NS
f is called

The global g is never called by NS::f! Is there something wrong? Please leave a feedback if you have an answer.