Search code examples
c++argument-dependent-lookup

Rules for Argument Dependent name lookup in C++


There have been some questions on SO recently on ADL that have got me thinking. Basically, I am confused which header files compiler can search when performing ADL ? Is it only the ones included by the user's code or can it include the other header files in which the same namespace which is being used in the user's code ? For example. std namespace spans across multiple header files. However, I may include only a subpart of it. Now if I define a function which is not in this subset of header files but is there in the std namespace (in the file I have not included), would it still be a ambiguous call ? I got this doubts mostly because of the discussion on this question


Solution

  • Here's how it works... There are 3 basic steps to compiling source into an executable:

    1. preprocessing
    2. compilation
    3. linking

    There is zero overlap in these steps in C++. Include directives are preprocessor directives and therefore happen before compilation. Template instantiation is a part of compilation, therefore it happens after preprocessing. Compilers do not search outside of the current translation unit for anything. Thus no, ADL, a compile time event, cannot search headers that where not included.

    The problem with your code linked in the comment to Buzz is that you can't know what headers are included or not by the standard headers. (Well, you can know if you go looking in them to find out, but the standard doesn't say.) Any one of your headers could, and apparently did, include <algorithm>. Once that happens:

    http://www2.roguewave.com/support/docs/leif/sourcepro/html/stdlibref/merge.html

    Your version becomes ambiguous with one of the definitions in namespace std because of ADL.