cplusplus.co.il

Koenig lookup

Posted on: 12/08/2009

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, since I did not bring the namespaced one (NS::f) into my own namespace: there was no such using-statement. However, this is not the case – and the compiler is actually unable to select which function to call.

This somewhat unexpected (at least to me) behaviour 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);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: