fork download
  1. #include <cstddef>
  2. #include <functional>
  3. #include <utility>
  4. #include <type_traits>
  5.  
  6. template <typename C, std::size_t N>
  7. struct NaryDispatch
  8. {
  9. template <typename T, std::size_t K, typename ...Args>
  10. struct function_maker
  11. {
  12. using type = typename function_maker<T, K - 1, T, Args...>::type;
  13. };
  14.  
  15. template <typename T, typename ...Args>
  16. struct function_maker<T, 0, Args...>
  17. {
  18. using type = std::function<void(Args...)>;
  19. };
  20.  
  21. using f_type = typename function_maker<C &, N>::type;
  22.  
  23. template <typename F>
  24. NaryDispatch(F && f) : fn_(std::forward<F>(f)) {}
  25.  
  26. template <typename ...Args,
  27. typename = typename std::enable_if<sizeof...(Args) == N>::type>
  28. void run(Args &&... args)
  29. {
  30. fn_(std::forward<Args>(args)...);
  31. }
  32.  
  33. f_type fn_;
  34. };
  35.  
  36.  
  37. #include <iostream>
  38.  
  39. void print(const char * msg, int a, int b, int c)
  40. {
  41. std::cout << msg << ": [" << a << ", " << b << ", " << c << "]\n";
  42. }
  43.  
  44. int main()
  45. {
  46. int x = 1, y = 2, z = 3;
  47.  
  48. print("Before", x, y, z);
  49.  
  50. NaryDispatch<int, 3> d([](int & a, int & b, int & c){ print("During", a++, b++, c++); });
  51. d.run(x, y, z);
  52.  
  53. print("After", x, y, z);
  54. }
  55.  
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
Before: [1, 2, 3]
During: [1, 2, 3]
After: [2, 3, 4]