QDebug-like structure: determine end of input via `operator<<`

448 views Asked by At

Qt has a nice debug feature, called like that

qDebug() << first_qobject << second_qobject;

it produces a line with some "standard to-string" of the objects and -- and that's the important part -- prints a \n and flushed the steam after second_object. I want to reproduce that behaviour by a convention that all of my classes have a std::string to_string() method which I call:

struct myDebug{
   template<typename T>
   myDebug& operator<<(T t){
       std::cout << t.to_string() << " "; // space-separated
       return *this;
   }
};

struct Point{
    std::string to_string(){ return "42"; }
};

myDebug() << Point() << Point(); // should produce "42 42" plus a newline (which it doesn't)

My question is now: Is there a way to find out that after returning *this the second time the returned object is not called any more? So that I can then print the std::endl? qDebug() seems to be able to do that.

1

There are 1 answers

0
wal-o-mat On

Found the solution and found out that my question is also a duplicate:

How does QDebug() << stuff; add a newline automatically?

In short, this can be done by implementing the destructor and just create temporary MyDebug objects like I did it in the code above and qDebug does it:

MyDebug() << foo << bar;
// will be destroyed after passing bar, and in the destructor I can now flush.