fork(3) download
  1. #include <iostream>
  2. #include <tuple>
  3. #include <functional>
  4. #include <string>
  5. using namespace std;
  6.  
  7. template <size_t N>
  8. struct apply_tuple_func
  9. {
  10. template<typename F, typename T, typename... A>
  11. static inline auto apply(F&& f, T&& t, A&&... a) ->
  12. decltype(
  13. apply_tuple_func<N-1>::apply(
  14. std::forward<F>(f),
  15. std::forward<T>(t),
  16. std::get<N-1>(std::forward<T>(t)),
  17. std::forward<A>(a)...))
  18. {
  19. return apply_tuple_func<N-1>::apply(
  20. std::forward<F>(f),
  21. std::forward<T>(t),
  22. std::get<N-1>(std::forward<T>(t)),
  23. std::forward<A>(a)...);
  24. }
  25. };
  26.  
  27. template <>
  28. struct apply_tuple_func<0>
  29. {
  30. template<typename F, typename T, typename... A>
  31. static inline auto apply(F&& f, T&&, A&&... a) ->
  32. decltype(
  33. std::forward<F>(f)(std::forward<A>(a)...))
  34. {
  35. return std::forward<F>(f)(std::forward<A>(a)...);
  36. }
  37. };
  38.  
  39. template <typename F, typename T>
  40. inline auto apply_tuple(F&& f, T&& t) ->
  41. decltype(
  42. apply_tuple_func<
  43. std::tuple_size<typename std::decay<T>::type>::value>
  44. ::apply(
  45. std::forward<F>(f),
  46. std::forward<T>(t)))
  47. {
  48. return apply_tuple_func<
  49. std::tuple_size<typename std::decay<T>::type>::value>
  50. ::apply(std::forward<F>(f), std::forward<T>(t));
  51. }
  52.  
  53. /*
  54.  
  55. FUN STUFF BELOW:
  56.  
  57. This will only run one specific function type,
  58. but you could do stuff through other fun means to make it run other things
  59.  
  60. */
  61.  
  62. template<typename R, typename... A>
  63. R test(const std::function<R(A...)>& func)
  64. {
  65. std::tuple<int, float, string> a(5, 2.3, "Some text");
  66. return apply_tuple(func, a);
  67. }
  68.  
  69. void test2(int i, float f, string s)
  70. {
  71. cout << i << " " << f << " " << s << endl;
  72. }
  73.  
  74. int main() {
  75. test(std::function<void(int, float, string)>([](int i, float f, string s)
  76. {
  77. cout << i << " " << f << " " << s << endl;
  78. }));
  79. test(std::function<void(int, float, string)>(&test2));
  80. return 0;
  81. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
5 2.3 Some text
5 2.3 Some text