QDebug() <<东西;自动添加换行符? [英] How does QDebug() << stuff; add a newline automatically?

查看:73
本文介绍了QDebug() <<东西;自动添加换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现我自己的 qDebug() 样式调试输出流,这基本上是我目前所拥有的:

I'm trying to implement my own qDebug() style debug-output stream, this is basically what I have so far:

struct debug
{
#if defined(DEBUG)
    template<typename T>
    std::ostream& operator<<(T const& a) const
    {
        std::cout << a;
        return std::cout;
    }
#else
    template<typename T>
    debug const& operator<<(T const&) const
    {
        return *this;
    }

    /* must handle manipulators (endl) separately:
     * manipulators are functions that take a stream& as argument and return a
     * stream&
     */
    debug const& operator<<(std::ostream& (*manip)(std::ostream&)) const
    {
        // do nothing with the manipulator
        return *this;
    }
#endif
};

典型用法:

debug() << "stuff" << "more stuff" << std::endl;

但我不想添加 std::endl;

But I'd like not to have to add std::endl;

我的问题基本上是,如何判断 operator<< 的返回类型何时不会被另一个 operator<<(和所以追加 endl)?

My question is basically, how can I tell when the return type of operator<< isn't going to be used by another operator<< (and so append endl)?

我能想到的实现这样的事情的唯一方法是创建一个与 qDebug() 创建的每个临时对象相关联的要打印的内容列表,然后打印所有内容,以及在 ~debug() 中使用尾随换行符(我可以做一些聪明的事情,比如插入空格),但显然这并不理想,因为我不能保证临时对象将被销毁直到范围结束(还是我?).

The only way I can think of to achieve anything like this would be to create a list of things to print with associated with each temporary object created by qDebug(), then to print everything, along with trailing newline (and I could do clever things like inserting spaces) in ~debug(), but obviously this is not ideal since I don't have a guarantee that the temporary object is going to be destroyed until the end of the scope (or do I?).

推荐答案

Qt 使用了类似于@Evan 的方法.见一个版本qdebug.h 的实现细节,但它们将所有内容流式传输到底层文本流,然后在销毁 qDebug() 返回的临时 QDebug 对象时刷新流和结束行.

Qt uses a method similar to @Evan. See a version of qdebug.h for the implementation details, but they stream everything to an underlying text stream, and then flush the stream and an end-line on destruction of the temporary QDebug object returned by qDebug().

这篇关于QDebug() &lt;&lt;东西;自动添加换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆