Just have a template parameter for the function-like type and take an argument of that type:
template <typename Function>
void foo(Function func) {
// Use func like so
func(10);
}
This is how the standard library algorithms do it. You could call it with a lambda like so:
foo([](int x) { std::cout << (x * 2) << std::endl; });
Of course, this requires that you specify in your documentation what kind of function you expect as the Function
type (until we get (until we get Concepts). Should it be unary? Binary? What type arguments should it take? What should it return?
Alternatively, you can take a function of a specific type by using std::function
:
int foo(std::function<int(char)> func) {
return func('a');
}
This time, foo
will only take function-like objects that take a char
argument and return an int
. There is one downside to this method, however, which is that the compiler is unlikely to inline any lambdas you pass as func
.
The most basic way to take a function as an argument is with a function pointer:
int foo(int (*func)(char)) {
return func('a');
}
However, this will only take function pointers (some lambdas can be converted to function pointers). It won't take functors or anything else of the sort.