This is because const lvalue ( T& ) references cannot bind to rvalues ββ( 3 and 4 are r values ββthat intuitively imply that they do not have an object identifier).
Try using lvalue references for const instead, which can be associated with rvalues ββ(after all, the min() function should not change the state of its arguments).
Also, don't forget the template<typename T> if you are writing a function template:
template<typename T>
For example, consider this small program:
Here is a living example .
UPDATE:
The above solution allows you to pass values ββof the same type to min() , otherwise the compiler will not be able to perform type inference (if the first and second arguments are of different types, what should T be?)
min(3.14, 42); // Huh? What is `T` here, `double` or `int`?
To force the compiler to use a specific type for T , you can explicitly specify a template argument:
min<double>(3.14, 42);
However, this is not a very elegant choice (the user must enter the correct template argument manually each time). Rather, you can let the function template take two parameters of the template type instead of one:
And use the std::common_type<> property (available since C ++ 11) to figure out the correct type, which will be used as the return type.
Once again, here is a living example .
source share