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

标签 c++ qt stream

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

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;

我的问题基本上是,我怎么知道 operator<< 的返回类型是什么时候?不会被另一个 operator<< 使用(所以追加 endl )?

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

最佳答案

这样就可以了:

struct debug {
    debug() {
    }

    ~debug() {
        std::cerr << m_SS.str() << std::endl;
    }

public:
    // accepts just about anything
    template<class T>
    debug &operator<<(const T &x) {
        m_SS << x;
        return *this;
    }
private:
    std::ostringstream m_SS;
};

应该让你做这样的事情:

debug() << "hello world";

我使用了这样的模式与锁相结合来提供类似流的日志系统,它可以保证日志条目是原子写入的。

注意:未经测试的代码,但应该可以工作:-)

关于c++ - QDebug() << 东西;自动添加换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2179623/

相关文章:

stream - 使用 PhantomData 和 unsafe 将流式迭代器作为普通迭代器处理

c++ - Qt多重继承出错

python - 如何清除 PyQt 中的绘图?

Java FileChannel.size() 与 File.length()

c++ - 让 g++ 使用 SHLD/SHRD 指令

ios - QT Creator iOS 错误 : The settings in the Devices window of Xcode might be incorrect

java - 根据 Java 中的值获取第一个 LinkedHashMap 键

c++ - 在主函数之上定义命名空间函数是否会导致内联函数?

c++ - 调整字节数组的大小

c++ - 简单的正则表达式似乎不工作 C++