Pass a function template as a parameter in C ++

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 highlighted,

 std::transform(left.begin(), left.end(), right.begin(), max_seq.begin(), &max<int>); 

But this does not compile because the compiler says

  note: template argument deduction/substitution failed 

I know that I can wrap "std :: max" inside a struct or inside lambda . But is there a way to directly use std::max without wrappers?

+5
source share
2 answers

std::max has several overloads, so the compiler cannot determine which one you want to call. Use static_cast to disambiguate and your code will be compiled.

 static_cast<int const&(*)(int const&, int const&)>(std::max) 

You should use lambda instead

 [](int a, int b){ return std::max(a, b); } 

Live demo

+6
source

Template expansion and initialization occur at compile time. Thus, you can pass a template function only to templates.

You can pass inline function (templated) at runtime (then this is a โ€œnormalโ€ C ++ function).

0
source

Source: https://habr.com/ru/post/1200863/


All Articles