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 behaviour for your implementation is correct, though you may not want that output. The problem with the return type in your code.
You may want to use trailing-return type if you can use C++11:
template <typename T, typename U>
auto max(T x, U y) -> decltype(x>y ? x : y) //C++11 only
{
return x>y ? x : y;
}
which would give this output:
17.9
17.9
I hope that is the desired output.
Online demo : http://ideone.com/2Sh5Y
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With