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

发布于 2024-12-27 03:33:01 字数 774 浏览 1 评论 0 原文

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() 似乎能够做到这一点。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

海的爱人是光 2025-01-03 03:33:01

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

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

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

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

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.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文