How does QDebug() lt;lt; stuff; add a newline automatically?(QDebug() lt;lt;东西;自动添加换行符?)
问题描述
我正在尝试实现我自己的 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() <<东西;自动添加换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:QDebug() <<东西;自动添加换行符?
基础教程推荐
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01