Reputation: 79
I'm trying to write a function (we'll call it function A) which can receive a user-defined function as input (for example, a user defined function which takes any number of variables and returns an integer -- We'll call this function B). I want to pass function B as a parameter for function A, only modify some of the variables in function B and call function B as many times as I need to from within function A.
I was thinking I can get this to work by making the variables of function B pointers and modifying the pointers at each call, however I don't know how to make it so I can call function B from within function A if the number of variables to be passed to function B are unknown.
Does anyone have any suggestions as to how I can pass a user-specified function as a parameter to another function?
Upvotes: 1
Views: 7667
Reputation: 119
Since you mentioned that you may modify variables in function B, function pointer is not a good choice,especially when C++ introduce the callable object, or std::function
. By constructing a class with operator ()
overloaded, you are able to treat the object of such class like a object and like a function pointer.
Another alternative is lambda introduced in C++11. You can simply write [A_variable_1, A_variable_2](auto parameter){ your code}
to use the variable in A and your own variable in B.
Upvotes: 3
Reputation: 36597
What you want is a pointer to a function.
For example, to pass a function that accepts an int
and returns a double.
#include <iostream>
double B(int x) // sample function that we call
{
return x*42.0;
}
void A(double (*f)(int))
{
for (int i = 0; i < 25; ++i)
std::cout << f(i) << '\n';
}
int main()
{
A(B);
}
If you want to pass a function that accepts a variable argument list, then modify the above. Look up in formation on the standard header <cstdarg>
for pointers on how to do that.
There are also techniques involving templates (specifically, templated functors) and lambdas (in C++11 and later). But using a pointer to a function is enough to get you started.
Upvotes: 1