类似QDebug的结构:通过`operator<<`确定输入结束

时间:2012-01-14 10:21:52

标签: c++ qdebug

Qt有一个很好的调试功能,就像那样

qDebug() << first_qobject << second_qobject;

它生成一条带有一些“标准字符串”对象的行 - 而且这是重要部分 - 在\n之后打印second_object并刷新蒸汽。我希望通过一个约定来重现这种行为,我的所有类都有std::string to_string()方法,我称之为:

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)

我现在的问题是:有没有办法在第二次返回*this之后发现返回的对象不再被调用?这样我就可以打印std::endl了? qDebug()似乎能够做到这一点。

1 个答案:

答案 0 :(得分:2)

找到解决方案并发现我的问题也是重复的:

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

简而言之,这可以通过实现析构函数来完成,只需创建临时MyDebug对象,就像我在上面的代码中所做的那样,qDebug就是这样做了:

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