One form of passing a generic function to be called is a callable templated type:
#include <functional>
#include <iostream>
template<typename F>
void callFoo(F f) {
f();
}
int main() {
callFoo(std::bind([](int a, int b) {std::cout << a << ' ' << b;}, 5, 6));
}
callFoo
takes a callable type, F
, and calls it. Around this call, you can, for example, do timer work to time the function. In main
, it's called with a lambda that has two parameters and the values given to those parameters bound to it. callFoo
can then call it without storing the arguments. This is very similar to taking a parameter with the type std::function<void()>
.
If, however, you don't want to use std::bind
, you can pass in the arguments separately with a couple changes:
template<typename F, typename... Args>
void callFoo(F f, Args... args) { //ignoring perfect forwarding
f(args...);
}
int main() {
callFoo(/*lambda*/, 5, 6);
}
In these cases, passing void functions makes sense. Indeed, return values can be used as parameters and passed in with std::ref
. If you plan on returning what the function returns, you'll have to handle the special case of the return type being void
, as you can't assign to a void
variable and return that. At this point, it's easier to direct you to my previous question on the matter. My use case for it turned out to be moot, but the solution works great for other uses.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…