fork download
  1. //http://stackoverflow.com/questions/24923211/how-to-output-values-to-a-tuple-of-streams-in-c11
  2. #include <iostream>
  3. #include <tuple>
  4. #include <utility>
  5. #include <fstream>
  6.  
  7.  
  8. template <unsigned int N>
  9. struct tee_stream
  10. {
  11. template <typename ...Args, typename T>
  12. static std::tuple<Args...> & print(std::tuple<Args...> & t, T && x)
  13. {
  14. std::get<sizeof...(Args) - N>(t) << x;
  15. tee_stream<N - 1>::print(t, std::forward<T>(x));
  16. return t;
  17. }
  18. };
  19.  
  20. template <>
  21. struct tee_stream<0>
  22. {
  23. template <typename ...Args, typename T>
  24. static std::tuple<Args...> & print(std::tuple<Args...> &, T &&) {}
  25. };
  26.  
  27. template <typename ...Args, typename T>
  28. std::tuple<Args...> & operator<<(std::tuple<Args...> & t, T && x)
  29. {
  30. return tee_stream<sizeof...(Args)>::print(t, std::forward<T>(x));
  31. }
  32.  
  33. template <typename ...Args, typename T>
  34. std::tuple<Args...> & operator<<(std::tuple<Args...> && t, T && x)
  35. {
  36. return tee_stream<sizeof...(Args)>::print(t, std::forward<T>(x));
  37. }
  38.  
  39. int main()
  40. {
  41. std::ofstream os("a.txt");
  42. auto t = std::tie(std::cout, os);
  43. t << "Foo" << "Bar\n";
  44. std::tie(std::cout, os) << "Foo" << "Bar\n";
  45. }
  46.  
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
FooBar
FooBar