Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mycout automatic endl

Tags:

c++

cout

I'd like implement class MyCout, which can provide possibility of automatic endl, i.e. this code

MyCout mycout;
mycout<<1<<2<<3;

outputs

123
//empty line here

Is it possible to implement class with such functionality?


UPDATE: Soulutions shouldn't be like that MyCout()<<1<<2<<3; i.e. they should be without creating temporary object

like image 495
eXXXXXXXXXXX2 Avatar asked Dec 14 '11 18:12

eXXXXXXXXXXX2


2 Answers

You can use the destructor of a temporary object to flush the stream and print a newline. The Qt debug system does this, and this answer describes how to do it.

like image 191
James Avatar answered Sep 29 '22 11:09

James


The following works in C++11:

#include <iostream>

struct myout_base { };
struct myout
{
  bool alive;
  myout() : alive(true) { }
  myout(myout && rhs) : alive(true) { rhs.alive = false; }
  myout(myout const &) = delete;
  ~myout() { if (alive) std::cout << std::endl; }
};

template <typename T>
myout operator<<(myout && o, T const & x)
{
  std::cout << x;
  return std::move(o);
}

template <typename T>
myout operator<<(myout_base &, T const & x)
{
  return std::move(myout() << x);
}

myout_base m_out;   // like the global std::cout

int main()
{
  m_out << 1 << 2 << 3;
}

With more work, you can add a reference to the actual output stream.

like image 26
Kerrek SB Avatar answered Sep 29 '22 13:09

Kerrek SB