How to use my logging class like a std C++ stream?(如何像 std C++ 流一样使用我的日志记录类?)
问题描述
我有一个工作记录器类,它将一些文本输出到富文本框(Win32,C++)中.问题是,我总是这样使用它:
I've a working logger class, which outputs some text into a richtextbox (Win32, C++). Problem is, i always end up using it like this:
stringstream ss;
ss << someInt << someString;
debugLogger.log(ss.str());
相反,像使用流一样使用它会方便得多:
instead, it would be much more convenient to use it like a stream as in:
debugLogger << someInt << someString;
有没有比将所有内容转发到内部字符串流实例更好的方法?如果这样做,我什么时候需要冲洗?
Is there a better way than forwarding everything to an internal stringstream instance? If'd do this, when would i need to flush?
推荐答案
您需要为您的班级适当地实施 operator <<.一般模式如下所示:
You need to implement operator << appropriately for your class. The general pattern looks like this:
template <typename T>
logger& operator <<(logger& log, T const& value) {
log.your_stringstream << value;
return log;
}
请注意,这会处理(非const)引用,因为该操作会修改您的记录器.另请注意,您需要返回 log 参数才能使链接正常工作:
Notice that this deals with (non-const) references since the operation modifies your logger. Also notice that you need to return the log parameter in order for chaining to work:
log << 1 << 2 << endl;
// is the same as:
((log << 1) << 2) << endl;
如果最里面的操作没有返回当前的 log 实例,所有其他操作要么在编译时失败(错误的方法签名)要么在运行时被吞没.
If the innermost operation didn't return the current log instance, all other operations would either fail at compile-time (wrong method signature) or would be swallowed at run-time.
这篇关于如何像 std C++ 流一样使用我的日志记录类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何像 std C++ 流一样使用我的日志记录类?
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
