Passing a function as a parameter in c++
There are at least three methods to pass a function argument in c++. Before we start, let us review the concept of the lambda expression.
Lambda expression
Lambda expression is an unnamed function that can be passed as a variable. Here is an example of a function in general form and lambda expression:
It is composited by [] capture list, () argument list and {} function body. Here is another example of a lambda expression:
Passing function as a parameter
There are three ways to pass a function as a parameter:
- Function Pointer
- Declare by std::function
- Function template
Method 1: Function Pointer
Con: Can not pass the local variable to the lambda function
void (*Func)(bool, int);
void is the return type which means nothing return.
(*Func) is the funciton pointer name.
(bool, int) is the arguments type.
Method 2: Declare by std::function
Pro: Valid to pass the local variable to the lambda function
Con: It may cause a performance drop but is not significant.
Bonus: std::bind can be used if we would like to pass a function from one object to another object in the std::function parameter.
std::bind(&I_have_a_usefull_function::func, true, std::placeholders::_1)
The first parameter "&I_have_a_usefull_function::func" is the function pointer you want to pass.
Other parameters are the argument pass to the funciton pointer. In this example, "this" is passed to inside the function body. In this example, the first argument is fixed as true. The second argument and third are set as placeholders 1 and 2 which can be input later.
Method 3: Function template
Pro:
- Valid to pass the local variable in the lambda function.
- No performance drop
Con:
- Template function must be written in the header file.
- Increase the compile time
References
https://blog.demofox.org/2015/02/25/avoiding-the-performance-hazzards-of-stdfunction/
Enjoy Reading This Article?
Here are some more articles you might like to read next: