Search code examples
c++compiler-errorsmaxfunction-templates

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


Solution

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