I thought we could call the template function without template parameter.
Why is this code working only if I specify the template parameter as double?
#include <iostream>
template <typename T>
T max(T x, T y)
{
return x > y ? x : y;
}
int main()
{
cout<<::max(3,4.7)<<"\n"; //Error
cout<<::max<int>(3,4.7)<<"\n"; //Error
cout<<::max<double>(3,4.7)<<"\n"; //Works
}
Template argument deduction needs to be applied to all arguments to the function, and in the first case (only case that does not compile) it will deduce the arguments to be
intanddouble. Because they do not match exactly, argument deduction fails. As you have already realized the answer is to disable type deduction and providing the type arguments yourself (second and third lines).For explicitly specialized function templates and ordinary functions, the arguments are then subject to implicit or user-defined type conversions (double to int, int to double, or via class constructors and conversion operators). During template argument deduction, no such type conversions will be performed, however.