Quick refresher: argument dependent lookup

Post by Nico Brailovsky @ 2017-01-04 | Permalink | Leave a comment

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).