gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:24:38 28 4
gpt4 key购买 nike

我正在尝试实现我自己的 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com