layout: post title: Passing a function as a parameter in c++ date: 2021-03-01 00:00:00 description: Passing a function as a parameter in c++ tags: programming cpp lambda categories: programming cpp —
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 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:
There are three ways to pass a function as a parameter:
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.
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.
Pro:
Con:
https://blog.demofox.org/2015/02/25/avoiding-the-performance-hazzards-of-stdfunction/