Quick refresher: argument dependent lookup

Since I wasted a few precious minutes stuck on an ADL problem, I figured I needed a quick reminder on how they work. Check this code: does it compile?

namespace N {
    int foo() {
    }
}

int main() {
    return foo();
}

Of course it doesn’t! You’d expect a ‘foo’ not declared/out of scope error from your compiler. What about this other example?

namespace N {
    struct Dummy;

    int foo(Dummy*) {
        return 0;
    }

    int foo() {
    }
}

int main() {
    return foo((N::Dummy*)0);
}

You’d be tempted to say it won’t work either. (Un?)fortunately, ‘argument dependant lookup’ is a thing, and the second code sample works. How? The compiler will look for ‘foo’ in the global namespace, and also in the namespace of the arguments to ‘foo’. Seeing ‘N::Dummy’ in there, the compiler is allowed to peak into the namespace N for method ‘foo’. Why? Short: operator overloading. Long: check here (the ‘Why ADL’ section is very good).

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