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".
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.
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.
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