Why are these overloads not ambiguous?

The following code compiles with gcc and clang.

template <typename T> struct identity { typedef T type; }; template <typename T> void foo(typename identity<T>::type); template <typename T> void foo(T); int main() { foo<int>(0); } 

It seems that overload resolution selects the first overload ( identity<T>::type one).

Can someone explain why overloads are not ambiguous? As far as I can tell, the only difference between the two is that the argument of the first is not the context to be deduced, and the argument of the second is not, but since I provide the argument of the template explicitly, I don’t understand why this matters.

+7
source share
1 answer

Both overloads are viable, but the former is more specialized than the latter, and therefore it is selected using overload resolution.

In paragraph 13.3.3 / 1 of the C ++ 11 standard on overload resolution:

[...] a viable function F1 is defined as a better function than another viable function F2 , if for all arguments i , ICSi(F1) not a worse conversion sequence than ICSi(F2) , and then

- for some argument j, ICSj(F1) is a better conversion sequence than ICSj(F2) , or, if not this,

- the context is initialization by user conversion (see 8.5, 13.3.1.5 and 13.3.1.6) and the standard conversion sequence from the return type F1 to the destination type (i.e., the initialization type of the object) is a better conversion sequence than the standard conversion sequence from return type F2 to destination type. [...] or, if not this,

- F1 is a function without a template, and F2 is a specialized function of a template or, if not this,

- F1 and F2 are specialized function templates, and the function template for F1 is more specialized than the template for F2 in accordance with the partial ordering rules described in 14.5.6.2.

The process of determining which of the two function templates is more specialized than the other is described in clause 14.5.6.2/2:

Partial ordering selects which of the two function templates is more specialized than the other, by converting each template in turn (see the next paragraph) and outputting the template argument using the type function. The deduction process determines whether one of the patterns is more specialized than the other. If therefore a more specialized template is the one selected by the partial sequencing process.

+7
source

All Articles