Search code examples
c++scopenamespacesargument-dependent-lookupusing-declaration

Does Argument-Dependent Lookup go before normal scope lookup?


This is the code in question that appears in §13.3 of "C++ Primer", 5ed:

void swap(Foo &lhs, Foo &rhs)
{
    using std::swap;
    swap(lhs.h, rhs.h); // uses the HasPtr version of swap
    // swap other members of type Foo
}

The book mentions the phenomenon of the class-specific swap not being hidden by the using declaration, and refers reader to §18.2.3:

enter image description here

I read that section and realized that this may be related to Argument-Dependent Lookup (ADL). The following is the excerption:

enter image description here

But I still have some vagueness in the understanding. My question is: does the ADL go before the normal scope lookup, or after the normal scope lookup? My current understanding is that ADL goes before the normal scope lookup, because otherwise it should be the std::swap that is used. I need confirmation if you think I am right, or please point out what mistake I've made if you think I am wrong. Thank you.


Solution

  • ADL doesn't go before, it's not preferred specially; the names found by ADL will be considered in addition to the names found by the usual name lookup.

    These function names are looked up in the namespaces of their arguments in addition to the scopes and namespaces considered by the usual unqualified name lookup.

    That means all the named found by ADL and usual name lookup will be considered in overload resolution; then the best match will be selected.

    In order to compile a function call, the compiler must first perform name lookup, which, for functions, may involve argument-dependent lookup, and for function templates may be followed by template argument deduction. If these steps produce more than one candidate function, then overload resolution is performed to select the function that will actually be called.