title: C++ template overload resolution called from template function pick candidate declared after template instantiation
body: <p>Here is a minimalist example of a very strange overload resolution from a template context:</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  // Types //
  struct I { int v; };
  
  template &lt;class T&gt;
  struct D { T t; };
  
  // Functions //
  
  // Overload 1
  template &lt;class T&gt;
  I f(T) { return {1}; }
  
  // Template indirection that calls f(T)
  template &lt;class T&gt;
  I g(D&lt;T&gt;) { return f(T{}); }
  
  // Non template indirection that calls f(T)
  I h(D&lt;I&gt;) { return f(I{}); }
  
  int main() {
      std::cout
          &lt;&lt; f(I{}).v     // f(I{}) overload called directly
          &lt;&lt; "\n"         //    =&gt; overload 1 called
          &lt;&lt; h(D&lt;I&gt;{}).v  // f(I{}) called though non-template
          &lt;&lt; "\n"         //    =&gt; overload 1 called
          &lt;&lt; g(D&lt;I&gt;{}).v  // f(I{}) called though template
          &lt;&lt; "\n";        //    =&gt; overload 2 actually called ???
  }
  
  // Overload 2
  // Should not be reachable as declared after all f(...) calls.
  // If was a candidate, would be chosen over 1.
  I f(I) { return {2}; }
  </code></pre>
  
  <p>This seem to be related to <a href="http://en.cppreference.com/w/cpp/language/adl" rel="nofollow">ADL</a> because if <code>I</code> is placed in a namespace "overload 1" is always called. </p>
  
  <p>I know that ADL is performed as if the call was made from the template instantiation point (<code>main</code>).</p>
  
  <blockquote>
    <p>For a dependent name used in a template definition, the lookup is postponed until the template arguments are known, at which time ADL examines function declarations with external linkage (until C++11) that are visible from the template definition context as well as in the template instantiation context, while non-ADL lookup only examines function declarations with external linkage (until C++11) that are visible from the template definition context.
    <a href="http://en.cppreference.com/w/cpp/language/unqualified_lookup#Template_definition" rel="nofollow">http://en.cppreference.com/w/cpp/language/unqualified_lookup#Template_definition</a></p>
  </blockquote>
  
  <p>But here "Overload 2" is declared AFTER <code>main</code>! <code>main</code> being the instanciation point of <code>g</code> and <code>f</code>, I assumed only function declared <em>before</em> <code>main</code> would be overload candidates.</p>
  
  <p>Note that this behaviour is related to <code>g</code> being template as <code>h</code> (<code>g</code>'s equivalent not template function) calls "Overload 1".</p>
  
  <p><strong>How can "overload 2" -being declared after <code>main</code>- ever be called ?</strong></p>
  
  <p>This behaviour has been reproduced with clang++ (3.8.1) and g++ (6.2.1).</p>