Re: Which function should get chosen
On Aug 6, 9:24 pm, Greg Herlihy <gre...@mac.com> wrote:
On Aug 6, 11:53 am, Kaba <n...@here.com> wrote:
In the following is a short code snippet concerning the
overload resolution with function templates. Which function
should be chosen in this case (i.e. what should the program
return)?
template <typename Type>
class Base {};
template <typename Type>
class A : public Base<Type> {};
template <typename Type>
int f(const Base<Type>& that) {return 0;}
template <typename Type>
int f(const Type& that) {return 1;}
int main()
{
A<int> a;
return f(a);
}
I am surprised to see that both Visual Studio 2008 and
Comeau C++ both choose the unrestricted template (return 1).
I'd argue that the other one containing Base<Type> parameter
is more specialized. What is going on?
The compiler does not even consider the function template with
the Base<Type> parameter, because a call to that function
would require converting the argument to a base class
template-id (specifically, converting the A<int> argument to a
B<int> parameter).
Now, according to =A714.8.2.1/3, this type of conversion is allowed:
"If P is a class, and P has the form template-id, then A can
be a derived class of the deduced A."
There is however one significant restriction:
"These alternatives are considered only if type deduction
would otherwise fail."
Since there is another f() function template for which type
deduction does succeed - the compiler does even consider the
other f() overload when resolving the f() function call.
I don't think that's right. The compiler applies type deduction
to both function templates, deducing Type == int for the first,
and Type == A<int> for the second. It then applies overload
resolution on the resulting functions: f( Base<int> const& )
(from the first template) and f( A< int > const& ) (from the
second template). Since the latter is a better match, it is
chosen. The choice of the "more specialize" is only used as a
tie breaker, if there would otherwise be ambiguity. That's not
the case here.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34