【发布时间】:2011-01-11 21:14:45
【问题描述】:
我正在尝试实现我自己的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() 中做一些聪明的事情,比如插入空格),但显然这并不理想,因为我不能保证临时对象会在作用域结束之前被销毁(或者我会这样做吗?)。
【问题讨论】:
-
qDebug()只是创建临时对象。按照符号,你会发现这样的东西:QDebug qDebug() { return QDebug(QtDebugMsg); }.