如何像 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.
相关文章