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() <<东西;自动添加换行符?
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
