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

Qt has a nice debugging feature called so

 qDebug() << first_qobject << second_qobject; 

it creates a line with some "standard string" of objects and - and what’s the important part - prints \n and blows off steam after second_object . I want to reproduce this behavior by convention that all 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) 

Now my question is: is there a way to find out that after returning *this second time, the returned object is no longer called? So that I can print std::endl ? qDebug() seems to be able to do this.

+4
source share
1 answer

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

Like QDebug () <<stuff; add new line automatically?

In short, this can be done by implementing a destructor and simply creating temporary MyDebug objects, as I did in the above code, and qDebug does this:

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

Source: https://habr.com/ru/post/1390974/


All Articles