fork download
  1. #include <iostream>
  2. #include <tuple>
  3. #include <cassert>
  4.  
  5. template<std::size_t ...Indices>
  6. struct index_tuple{
  7. };
  8. template<typename Left,typename Right>
  9. struct concat_index_tuple;
  10. template<std::size_t ...Lefts,std::size_t ...Rights>
  11. struct concat_index_tuple<index_tuple<Lefts...>,index_tuple<Rights...>>{
  12. using type = index_tuple<Lefts...,Rights...>;
  13. };
  14. template<std::size_t Beg,std::size_t End>
  15. struct make_index_tuple{
  16. using type = typename concat_index_tuple<
  17. index_tuple<Beg>,
  18. typename make_index_tuple<Beg + 1,End>::type
  19. >::type;
  20. };
  21. template<std::size_t End>
  22. struct make_index_tuple<End,End>{
  23. using type = index_tuple<End>;
  24. };
  25. template<typename Tuple>
  26. struct tuple_index;
  27. template<typename ...Ts>
  28. struct tuple_index<std::tuple<Ts...>>{
  29. using type = typename make_index_tuple<0,sizeof...(Ts) - 1>::type;
  30. };
  31.  
  32. struct outputter{
  33. std::ostream &os;
  34. outputter(std::ostream &s) : os(s){
  35. }
  36.  
  37. template<typename T>
  38. void operator ()(T const& v){
  39. os << v << std::endl;
  40. }
  41. };
  42. struct add_x{
  43. int i;
  44. add_x(int v) : i(v){
  45. }
  46.  
  47. template<typename T>
  48. void operator ()(T &v){
  49. v += i;
  50. }
  51. };
  52.  
  53. template<typename F,typename T>
  54. void work_impl(F func,std::size_t s,T &&x){
  55. assert(s == 0);
  56. func(std::forward<T>(x));
  57. }
  58. template<typename F,typename T,typename ...Us>
  59. void work_impl(F func,std::size_t s,T &&x,Us &&...xs){
  60. if(s){
  61. work_impl(func,s - 1,std::forward<Us>(xs)...);
  62. }
  63. else{
  64. func(std::forward<T>(x));
  65. }
  66. }
  67. template<typename F,typename Tuple,std::size_t ...Indices>
  68. void work_unpack(F func,std::size_t s,Tuple &&t,index_tuple<Indices...>){
  69. work_impl(func,s,std::get<Indices>(std::forward<Tuple>(t))...);
  70. }
  71. template<typename F,typename Tuple>
  72. void work(F func,std::size_t s,Tuple &&t){
  73. work_unpack(func,s,std::forward<Tuple>(t),typename tuple_index<typename std::remove_reference<Tuple>::type>::type{});
  74. }
  75.  
  76. int main() {
  77. int i;
  78. std::cout << "Enter index" << std::endl;
  79. std::cin >> i;
  80.  
  81. auto t = std::make_tuple(1,2.0,3ull,4.f);
  82. work(outputter{std::cout},i,t);
  83. work(add_x{2},i,t);
  84. work(outputter{std::cout},i,t);
  85. work(outputter{std::cout},i,std::make_tuple("a",42,3.14f,&i));
  86. return 0;
  87. }
Success #stdin #stdout 0s 3304KB
stdin
2
stdout
Enter index
3
5
3.14