fork(2) download
  1.  
  2. #include <iostream>
  3. #include <tuple>
  4. #include <sstream>
  5. #include <string>
  6. #include <vector>
  7. #include <memory>
  8.  
  9. //FRAMEWORK - HELPER ETC
  10.  
  11.  
  12. template<int ...>
  13. struct seq {};
  14.  
  15. template<int M, int ...N>
  16. struct genseq : genseq<M-1,M-1, N...> {};
  17.  
  18. template<int ...N>
  19. struct genseq<0,N...>
  20. {
  21. typedef seq<N...> type;
  22. };
  23.  
  24. template<typename...args>
  25. struct tuple_maker
  26. {
  27. template<int ...N>
  28. std::tuple<args...> make(std::istream & stream, const seq<N...> &)
  29. {
  30. return std::make_tuple(args(read_arg<N>(stream))...);
  31. }
  32. std::vector<std::string> m_params;
  33. std::vector<std::unique_ptr<std::stringstream>> m_streams;
  34. template<int Index>
  35. std::stringstream & read_arg(std::istream & stream)
  36. {
  37. if ( m_params.empty() )
  38. {
  39. std::string line;
  40. while ( std::getline(stream, line) ) //read all at once!
  41. {
  42. m_params.push_back(line);
  43. }
  44. }
  45. auto pstream = new std::stringstream(m_params.at(Index));
  46. m_streams.push_back(std::unique_ptr<std::stringstream>(pstream));
  47. return *pstream;
  48. }
  49. };
  50.  
  51. //PARSE FUNCTION
  52. template<typename... args>
  53. std::tuple<args...> parse(std::istream &stream)
  54. {
  55. const int N = sizeof...(args);
  56. return tuple_maker<args...>().make(stream, typename genseq<N>::type() );
  57. }
  58.  
  59. ///TEST CODE
  60.  
  61. template<int N>
  62. struct A
  63. {
  64. std::string data;
  65. A(std::istream & stream)
  66. {
  67. stream >> data;
  68. }
  69. friend std::ostream& operator << (std::ostream & out, A<N> const & a)
  70. {
  71. return out << "A" << N << "::data = " << a.data ;
  72. }
  73. };
  74. typedef A<1> A1;
  75. typedef A<2> A2;
  76. typedef A<3> A3;
  77.  
  78. int main()
  79. {
  80. std::stringstream ss("A1\nA2\nA3\n");
  81. auto tuple = parse<A1,A2,A3>(ss);
  82. std::cout << std::get<0>(tuple) << std::endl;
  83. std::cout << std::get<1>(tuple) << std::endl;
  84. std::cout << std::get<2>(tuple) << std::endl;
  85. }
  86.  
Success #stdin #stdout 0s 3072KB
stdin
Standard input is empty
stdout
A1::data = A1
A2::data = A2
A3::data = A3