Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a function template as a parameter in C++

Tags:

c++

templates

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?

like image 950
CS Pei Avatar asked Aug 21 '14 17:08

CS Pei


People also ask

Can a template be a template parameter?

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.

How do you call a function template?

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.

Which of the following can be passed to function template as an argument?

Explanation: A template parameter is a special kind of parameter that can be used to pass a type as argument.

What is parameterized template?

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.


1 Answers

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

like image 70
Praetorian Avatar answered Oct 03 '22 21:10

Praetorian