fork(1) download
  1. #include <iostream>
  2. #include <functional>
  3. #include <tuple>
  4. #include <iostream>
  5.  
  6. using namespace std::placeholders;
  7.  
  8. // simple function to be called
  9. double foo_fn(int x, float y, double z)
  10. {
  11. double res = x + y + z;
  12. std::cout << "foo_fn called. x = " << x << " y = " << y << " z = " << z
  13. << " res=" << res;
  14. return res;
  15. }
  16.  
  17. // helpers for tuple unrolling
  18. template<int ...> struct seq {};
  19. template<int N, int ...S> struct gens : gens<N-1, N-1, S...> {};
  20. template<int ...S> struct gens<0, S...>{ typedef seq<S...> type; };
  21.  
  22. // invocation helper
  23. template<typename FN, typename P, int ...S>
  24. double call_fn_internal(const FN& fn, const P& params, const seq<S...>)
  25. {
  26. return fn(std::get<S>(params) ...);
  27. }
  28. // call function with arguments stored in std::tuple
  29. template<typename Ret, typename ...Args>
  30. Ret call_fn(const std::function<Ret(Args...)>& fn,
  31. const std::tuple<Args...>& params)
  32. {
  33. return call_fn_internal(fn, params, typename gens<sizeof...(Args)>::type());
  34. }
  35.  
  36.  
  37. int main(void)
  38. {
  39. // arguments
  40. std::tuple<int, float, double> t = std::make_tuple(1, 5, 10);
  41. // function to call
  42. std::function<double(int, float, double)> fn = foo_fn;
  43.  
  44. // invoke a function with stored arguments
  45. call_fn(fn, t);
  46. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
foo_fn called. x = 1 y = 5 z = 10 res=16