I know this is because the return type of the template function is same as that of the first argument (T).
How can I modify this template so that, it behaves correctly in all cases?
#include <iostream>
using namespace std;
template <typename T, typename U>
T max(T x, U y)
{
return x>y ? x : y;
}
int main()
{
cout<<max(17.9,17)<<"\n";
cout<<max(17,17.9)<<"\n";
}
Output:
17.9
17
The output is correct. You never specified a type, so complaining that it didn’t use the type you wanted it to use is not reasonable. If you want a specific type, you have to ensure both parameters are that type.
You could cast the first parameter to a
double. Or you could specifically invokemax<double, double>. You could also specializemax<int, double>and similar combinations if you really, really wanted to.