4

Qt 有一个很好的调试功能,像这样调用

qDebug() << first_qobject << second_qobject;

它产生一条带有一些“标准到字符串”的对象的行,并且 - 这是重要的部分 - 打印 a\n并在之后冲洗蒸汽second_objectstd::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()似乎能够做到这一点。

4

1 回答 1

2

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

QDebug() << 东西; 自动添加换行符?

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

MyDebug() << foo << bar;
// will be destroyed after passing bar, and in the destructor I can now flush.
于 2012-01-14T10:31:09.543 回答