fork(3) download
  1. #include <functional>
  2. #include <tuple>
  3.  
  4. // apply a functor to every element of a tuple
  5. namespace Detail {
  6. template <std::size_t i, typename Tuple, typename F>
  7. typename std::enable_if<i == std::tuple_size<Tuple>::value>::type
  8. ForEachTupleImpl(Tuple& t, F& f)
  9. {
  10. }
  11.  
  12. template <std::size_t i, typename Tuple, typename F>
  13. typename std::enable_if<i != std::tuple_size<Tuple>::value>::type
  14. ForEachTupleImpl(Tuple& t, F& f)
  15. {
  16. f(std::get<i>(t));
  17. ForEachTupleImpl<i+1>(t, f);
  18. }
  19.  
  20. }
  21.  
  22. template <typename Tuple, typename F>
  23. void ForEachTuple(Tuple& t, F& f)
  24. {
  25. Detail::ForEachTupleImpl<0>(t, f);
  26. }
  27.  
  28. struct A
  29. {
  30. A() : a(0) {}
  31. A(A& a) = delete;
  32. A(const A& a) = delete;
  33.  
  34. int a;
  35. };
  36.  
  37. int main()
  38. {
  39. // create a tuple of types and initialise them with zeros
  40. using T = std::tuple<A, A, A>;
  41. T t;
  42.  
  43. // creator a simple function object that increments the objects member
  44. struct F
  45. {
  46. void operator()(A& a) const { a.a++; }
  47. } f;
  48.  
  49. // if this works I should end up with a tuple of A's with members equal to 1
  50. ForEachTuple(t, f);
  51. return 0;
  52. }
Success #stdin #stdout 0s 3336KB
stdin
Standard input is empty
stdout
Standard output is empty