c++ - how do we pass an arbitrary function to another function -
i have question continuing post function passed template argument. in provided code:
#include <iostream> void add1(int &v) { v+=1; } void add2(int &v) { v+=2; } template <void (*t)(int &)> void dooperation() { int temp=0; t(temp); std::cout << "result " << temp << std::endl; } int main() { dooperation<add1>(); dooperation<add2>(); }
what 3rd function has different parameter set layout, e.g.
double add3(double v1, double v2) { homecoming v1+v2; }
if not achievable using template @ all, how pass arbitrary function function? , how handle parameter set kinds of possibilities? know python may able passing tuple (kwargs**), not sure c/c++.
one form of passing generic function called 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 << << ' ' << b;}, 5, 6)); }
callfoo
takes callable type, f
, , calls it. around call, can, example, timer work time function. in main
, it's called lambda has 2 parameters , values given parameters bound it. callfoo
can phone call without storing arguments. similar taking parameter type std::function<void()>
.
if, however, don't want utilize std::bind
, can pass in arguments separately 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, homecoming values can used parameters , passed in std::ref
. if plan on returning function returns, you'll have handle special case of homecoming type beingness void
, can't assign void
variable , homecoming that. @ point, it's easier direct previous question on matter. utilize case turned out moot, solution works great other uses.
c++
No comments:
Post a Comment