Re: Which function should get chosen
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.
Greg