fork(20) download
  1. #include <string>
  2. #include <iostream>
  3. #include <tuple>
  4. #include <vector>
  5.  
  6. namespace detail
  7. {
  8. template<int... Is>
  9. struct seq { };
  10.  
  11. template<int N, int... Is>
  12. struct gen_seq : gen_seq<N - 1, N - 1, Is...> { };
  13.  
  14. template<int... Is>
  15. struct gen_seq<0, Is...> : seq<Is...> { };
  16.  
  17. template<typename T, typename F, int... Is>
  18. void for_each(T&& t, F f, seq<Is...>)
  19. {
  20. auto l = { (f(std::get<Is>(std::forward<T>(t))), 0)... };
  21. }
  22. }
  23.  
  24. template<typename... Ts, typename F>
  25. void for_each_in_tuple(std::tuple<Ts...> const& t, F f)
  26. {
  27. detail::for_each(t, f, detail::gen_seq<sizeof...(Ts)>());
  28. }
  29.  
  30. template<typename... Ts>
  31. struct TupleOfVectors
  32. {
  33. std::tuple<std::vector<Ts>...> t;
  34.  
  35. void do_something_to_each_vec()
  36. {
  37. for_each_in_tuple(t, tuple_vector_functor());
  38. }
  39.  
  40. struct tuple_vector_functor
  41. {
  42. template<typename T>
  43. void operator () (T const &v)
  44. {
  45. std::cout << "{ ";
  46. bool first = true;
  47. for (auto const& x : v)
  48. {
  49. if (!first) { std::cout << ", "; };
  50. std::cout << x;
  51. first = false;
  52. }
  53. std::cout << " }" << std::endl;
  54. }
  55. };
  56. };
  57.  
  58. int main()
  59. {
  60. TupleOfVectors<int, double, std::string> tv;
  61. std::get<0>(tv.t).push_back(42);
  62. std::get<0>(tv.t).push_back(1729);
  63.  
  64. std::get<1>(tv.t).push_back(3.14);
  65.  
  66. std::get<2>(tv.t).push_back("Hello");
  67. std::get<2>(tv.t).push_back("World");
  68. std::get<2>(tv.t).push_back("of");
  69. std::get<2>(tv.t).push_back("Tuples!");
  70.  
  71. tv.do_something_to_each_vec();
  72. }
  73.  
Success #stdin #stdout 0s 2988KB
stdin
Standard input is empty
stdout
{ 42, 1729 }
{ 3.14 }
{ Hello, World, of, Tuples! }