This question already has an answer here:
- How to implement generic max function? 5 answers
This question can be stupid depending how you would look at it.
Out of curiosity I wanted to implement a get_max
function which can return the maximum of two similar or distinct types. I know std already has this but:
template <class T, class U>
T get_max(T lh, U rh) {
if(lh >= rh) return lh;
else return rh;
}
Somewhere in the main:
int a = 10;
double d = 20.01;
std::cout << "a=" << a << "\nd=" << d << "\nget_max=" <<
get_max(a,d) << std::endl;
The result surprised me:
a=10
d=20.01
get_max=20
I was expecting to have get_max
to output 20.01, but it outputed an int. I can understand because the first argument is int
then the T
in the function returns T
which in this case is obviously int
so the function returns the bigger of the two arguments, but casts it to the type of the first argument.
Is there a way to somehow make the code smart to return the double
or the type with higher precision?
I know for a fact that passing the double
as the first argument would be a naive way of fixing the problem!
Aucun commentaire:
Enregistrer un commentaire