For example, I want to get a list of maximum values from two sequences, left
and right
, and save the results in max_seq
, which are all previously defined and allocated,
std::transform(left.begin(), left.end(), right.begin(), max_seq.begin(), &max<int>);
But this won't compile because the compiler says
note: template argument deduction/substitution failed
I know I can wrapper "std::max" inside a struct
or inside a lambda
. But is there a way directly
use std::max
without wrappers?
Templates can be template parameters. In this case, they are called template parameters. The container adaptors std::stack, std::queue, and std::priority_queue use per default a std::deque to hold their arguments, but you can use a different container.
A function template starts with the keyword template followed by template parameter(s) inside <> which is followed by the function definition. In the above code, T is a template argument that accepts different data types ( int , float , etc.), and typename is a keyword.
Explanation: A template parameter is a special kind of parameter that can be used to pass a type as argument.
In UML models, template parameters are formal parameters that once bound to actual values, called template arguments, make templates usable model elements. You can use template parameters to create general definitions of particular types of template.
std::max
has multiple overloads, so the compiler is unable to determine which one you want to call. Use static_cast
to disambiguate and your code will compile.
static_cast<int const&(*)(int const&, int const&)>(std::max)
You should just use a lambda instead
[](int a, int b){ return std::max(a, b); }
Live demo
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