Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I put this question to the library authors at MS and got an extremely informative response from Stephan Lavavej, so I give him full credit for this information.</p> <p>The compile error you get in the template case is due to the fact that template argument deduction runs before overload resolution, and template argument deduction needs exact matches to add anything to the overload set. </p> <p>In detail, template argument deduction looks at each pair of parameter type P and argument type A, and tries to find template substitutions that will make A <em>exactly</em> match P. After finding matches for each argument, it checks for consistency (so that if you call <code>bar(foo&lt;T&gt;, foo&lt;T&gt;)</code> with T=int for the first parameter and T=double as the second, it also fails). Only after exact, consistent matches are successfully substituted in the function signature is that signature added to the set of candidate functions for overload resolution.</p> <p>Only after all ordinary functions (found through name lookup) and matching function template signatures have been added to the overload set is overload resolution run, at which point all of these function signatures are evaluated for a "best match", during which time implicit conversions will be considered.</p> <p>For the <code>operator+(foo&lt;T&gt;, foo&lt;T&gt;)</code> case with <code>foo&lt;int&gt; + 5</code>, template argument deduction can find no substitution for T that will make the expression <code>foo&lt;T&gt;</code> <em>exactly</em> match <code>int</code>, so that overload of operator+ gets tossed out as a candidate and the implicit conversion is never even seen.</p> <p>The opinion here seems to be that this is generally a good thing, as it makes templates much more predictable, leaving the realm of strange implicit behaviors to overload resolution.</p> <p>The standard has plenty to say about this at: </p> <p><strong>14.8.2.1 Deducing template arguments from a function call</strong></p> <p>"Template argument deduction is done by comparing each function template parameter type (call it P) with the type of the corresponding argument of the call (call it A) as described below. ...</p> <p>... In general, the deduction process attempts to find template argument values that will make the deduced A identical to A (after the type A is transformed as described above)"</p> <p>It goes on to list a few special cases where this rule has exceptions involving cv-qualifiers (so T&amp; will be compatible with const T&amp;), and matching of derived classes (it can in some cases match Derived&amp; to Base&amp;) but basically, exact matching is the rule.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload