如何QDebug()<<东东;自动添加换行符? [英] How does QDebug() << stuff; add a newline automatically?
问题描述
我试图实现我自己的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;
我的问题基本上是,我如何告诉何时返回类型的操作符<将不被另一个运营商使用< (所以追加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)?
我可以想到的唯一的方法是实现这样的东西是创建一个列表,打印每个临时对象由debug()创建,然后在〜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 debug(), 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()<<东东;自动添加换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!