Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it an error to use std::max() with two different types of argument?

Is there any reason that c++ compiler gives error when using two different numeric variable types in std::max() function? (e.g. int and long).

I mean something like: "Sometimes we have this problem when using std::max() function for two different numeric variable types, so the compiler gives error to prevent this problem".

like image 347
Ali Avatar asked Sep 19 '25 09:09

Ali


2 Answers

The compiler produces an error because it cannot perform type deduction for the template argument of std::max. This is how std::max template is declared: the same type (template parameter) is used for both arguments. If the arguments have different types, the deduction becomes ambiguous.

If you work around the deduction ambiguity by supplying the template argument explicitly, you will be able to use different types as std::max arguments

std::max(1, 2.0); // Error
std::max<double>(1, 2.0); // OK

The reason why std::max insists on using a common type for its arguments (instead of using two independent types) is described in @bolov's answer: the function actually wants to return a reference to the maximum value.

like image 144
AnT Avatar answered Sep 21 '25 02:09

AnT


std::max returns a reference to the argument that has the maximum value. The main reason it is this way is because it is a generic function and as such it can be used with types expensive to copy. Also you might actually need just a reference to the object, instead a copy of it.

And because it returns a reference to a argument, all arguments must be of the same type.

like image 33
bolov Avatar answered Sep 21 '25 02:09

bolov