fork download
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4.  
  5. class Stream;
  6. class StreamTemporary
  7. {
  8. public:
  9. StreamTemporary(Stream& s) : _s(s) {}
  10. StreamTemporary& operator<<(const string& str);
  11. ~StreamTemporary();
  12. private:
  13. Stream& _s;
  14. };
  15.  
  16. class Stream
  17. {
  18. public:
  19. StreamTemporary operator<<(const string& str)
  20. {
  21. write(str);
  22. return StreamTemporary(*this);
  23. }
  24. private:
  25. friend class StreamTemporary;
  26. // write without returning a temporary
  27. void write(const string& str)
  28. {
  29. cout << str;
  30. }
  31. };
  32.  
  33. StreamTemporary::~StreamTemporary()
  34. {
  35. // make sure not to call operator<< here or there will be infinite recursion
  36. _s.write("\n");
  37. }
  38.  
  39. StreamTemporary& StreamTemporary::operator<<(const string& str)
  40. {
  41. // make sure not to call operator<< here or extra newlines will be printed
  42. _s.write(str);
  43. }
  44.  
  45. int main() {
  46. Stream myStream;
  47. myStream << "Hello, " << "World!";
  48. myStream << "a" << "b" << "c";
  49. myStream << "end of program";
  50. }
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
Hello, World!
abc
end of program