fork(1) download
  1. #include<tuple>
  2. #include<vector>
  3.  
  4. #include<iostream>
  5.  
  6. template<typename... Ps>
  7. inline void
  8. cross_imp(std::tuple<Ps...> pref, std::vector<std::tuple<Ps...>>& out)
  9. {
  10. out.push_back(pref);
  11. }
  12.  
  13. template<typename... Ps, typename H, typename... Ts>
  14. inline void
  15. cross_imp(std::tuple<Ps...> pref,
  16. std::vector<std::tuple<Ps..., H, Ts...>>& out,
  17. std::vector<H> h, std::vector<Ts>... t)
  18. {
  19. for(H he: h)
  20. cross_imp(std::tuple_cat(pref, std::make_tuple(he)), out, t...);
  21. }
  22.  
  23. template<typename... Ts>
  24. std::vector<std::tuple<Ts...>>
  25. cross(std::vector<Ts>... in)
  26. {
  27. std::vector<std::tuple<Ts...>> res;
  28. cross_imp(std::tuple<>(), res, in...);
  29. return res;
  30. }
  31.  
  32. #include <cstddef>
  33. #include <tuple>
  34. #include <type_traits>
  35. #include <utility>
  36.  
  37. template<size_t N>
  38. struct Apply {
  39. template<typename F, typename T, typename... A>
  40. static inline auto apply(F&& f, T && t, A &&... a)
  41. -> decltype(Apply<N-1>::apply(::std::forward<F>(f), ::std::forward<T>(t),
  42. ::std::get<N-1>(::std::forward<T>(t)), ::std::forward<A>(a)...
  43. ))
  44. {
  45. return Apply<N-1>::apply(::std::forward<F>(f), ::std::forward<T>(t),
  46. ::std::get<N-1>(::std::forward<T>(t)), ::std::forward<A>(a)...
  47. );
  48. }
  49. };
  50.  
  51. template<>
  52. struct Apply<0> {
  53. template<typename F, typename T, typename... A>
  54. static inline auto apply(F && f, T &&, A &&... a)
  55. -> decltype(f(::std::forward<A>(a)...))
  56. {
  57. return f(::std::forward<A>(a)...);
  58. }
  59. };
  60.  
  61. template<typename F, typename T>
  62. inline auto apply(F && f, T && t)
  63. -> decltype(Apply< ::std::tuple_size<
  64. typename ::std::decay<T>::type
  65. >::value>::apply(::std::forward<F>(f), ::std::forward<T>(t)))
  66. {
  67. return Apply< ::std::tuple_size<
  68. typename ::std::decay<T>::type
  69. >::value>::apply(f, ::std::forward<T>(t));
  70. }
  71.  
  72. int main() {
  73. std::vector<int> is = { 2, 5, 9 };
  74. std::vector<char const*> cps = { "foo","bar" };
  75. std::vector<float> fs = { 1.5, 9.3, 1.2 };
  76. std::vector<double> ds = { 9.2,-2.1, 2.3 };
  77.  
  78. #ifdef DIRECT_CALL
  79. auto result = cross( is, cps, fs, ds );
  80. #else
  81. std::vector< std::tuple<int,char const*,float,double> > result
  82. = apply( cross, std::make_tuple( is, cps, fs, ds ));
  83. #endif
  84.  
  85. for(auto& a: result) {
  86. std::cout << '{'
  87. << std::get<0>(a) << ','
  88. << std::get<1>(a) << ','
  89. << std::get<2>(a) << ','
  90. << std::get<3>(a)
  91. << '}' << std::endl;
  92. }
  93. }
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty