fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <tuple>
  4.  
  5. // helper function to print a tuple of any size
  6. template<class Tuple, std::size_t N>
  7. struct TuplePrinter {
  8. static void print(const Tuple& t)
  9. {
  10. TuplePrinter<Tuple, N-1>::print(t);
  11. std::cout << ", " << std::get<N-1>(t);
  12. }
  13. };
  14.  
  15. template<class Tuple>
  16. struct TuplePrinter<Tuple, 1> {
  17. static void print(const Tuple& t)
  18. {
  19. std::cout << std::get<0>(t);
  20. }
  21. };
  22.  
  23. template<class Tuple>
  24. struct TuplePrinter<Tuple, 0> {
  25. static void print(const Tuple& t)
  26. {
  27. }
  28. };
  29.  
  30. template<class... Args>
  31. void print(const std::tuple<Args...>& t)
  32. {
  33. std::cout << "(";
  34. TuplePrinter<decltype(t), sizeof...(Args)>::print(t);
  35. std::cout << ")\n";
  36. }
  37.  
  38. struct Row
  39. {
  40. template <int N, typename ... Args> struct Helper;
  41.  
  42. template <typename Arg1> struct Helper<1, Arg1>
  43. {
  44. static std::tuple<Arg1> getResult(Row& r)
  45. {
  46. return std::make_tuple(r.getResult<Arg1>(0));
  47. }
  48. };
  49.  
  50. template <int N, typename Arg1, typename ... Args>
  51. struct Helper<N, Arg1, Args...>
  52. {
  53. static std::tuple <Arg1, Args ...> getResult(Row& r)
  54. {
  55. return std::tuple_cat(std::make_tuple(r.getResult<Arg1>(N-1)),
  56. Helper<N-1, Args...>::getResult(r));
  57. }
  58. };
  59.  
  60. template <typename Arg> Arg getResult(int index)
  61. {
  62. // This is where the value needs to be extracted from the row.
  63. // It is a dummy implementation for testing purposes.
  64. return Arg{};
  65. }
  66.  
  67. template <typename ... Args>
  68. std::tuple <Args ...> getResult()
  69. {
  70. return Helper<sizeof...(Args), Args...>::getResult(*this);
  71. }
  72. };
  73.  
  74. int main()
  75. {
  76. Row r;
  77. auto res1 = r.getResult<std::string>();
  78. auto res2 = r.getResult<int>();
  79. auto res3 = r.getResult<int, double, int>();
  80. auto res4 = r.getResult<int, int, double, double>();
  81. auto res5 = r.getResult<std::string, std::string, int, int, double, double>();
  82.  
  83. print(res1);
  84. print(res2);
  85. print(res3);
  86. print(res4);
  87. print(res5);
  88.  
  89. return 0;
  90. }
  91.  
Success #stdin #stdout 0s 3300KB
stdin
Standard input is empty
stdout
()
(0)
(0, 0, 0)
(0, 0, 0, 0)
(, , 0, 0, 0, 0)