Koenig lookup

What would you expect to happen in the following code?

namespace NS {
    struct A {};
    void f (A a) {}
}

void f (NS::A a) {}

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

With no prior knowledge, I would expect the global f() function (::f) to be called, even more so since I did not bring the namespaced one (NS::f) into my own namespace. However, this is not the case – and the compiler is actually unable to determine which function to call.

This somewhat unexpected (at least to me) behavior is caused by a mechanism called “argument-dependent lookup” (aka “Koenig lookup”), described here.

We could easily avoid the ambiguity caused by the mechanism in this case by using either

NS::f(a);

or

::f(a);

Leave a Reply