In below program why does the compiler generate an error for the call to the printMax template function and not the call to the printMaxInts function?
#include <iostream>
template<class A>
void printMax(A a,A b)
{
A c = a>b?a:b;
std::cout<<c;
}
void printMaxInts(int a ,int b)
{
int c = a>b?a:b;
std::cout<<c;
}
int main()
{
printMax(1,14.45);
printMaxInts(1,24);
}
In order for the compiler to deduce the template parameter
Afrom the arguments passed to the function template, both arguments,aandbmust have the same type.Your arguments are of type
intanddouble, and so the compiler can’t deduce what type it should actually use forA. ShouldAbeintor should it bedouble?You can fix this by making both arguments have the same type:
or by explicitly specifying the template parameter:
The reason that the call to the non-template function can be called is that the compiler does not need to deduce the type of the parameters: it knows the type of the parameters because you said what they were in the function declaration:
Both
aandbare of typeint. When you pass adoubleas an argument to this function, thedouble -> intstandard conversion is performed on the argument and the function is called with the resultingint.