如何使用我的日志类像std C ++流? [英] How to use my logging class like a std C++ stream?
问题描述
我有一个工作logger类,它输出一些文本到一个richtextbox(Win32,C ++)。问题是,我总是最终使用它像这样:
stringstream ss;
ss<<一些<< someString;
debugLogger.log(ss.str());
,使用它就像一个流将更加方便:
debugLogger<<一些<< someString;
有没有更好的方法转发一切到一个内部stringstream实例?
您需要实现运算符< ;< $ / code>。一般模式如下:
模板< typename T>
logger& operator<<<(logger& log,T const& value){
log.your_stringstream<<值;
return log;
}
注意这是处理(非 - const
)引用,因为操作修改您的记录器。另请注意,您需要返回 log
参数才能使链接工作:
log<< 1<< 2<< endl;
//与以下相同:
((log << 1)<< 2)< endl;
如果最内层操作未返回当前 log
instance,所有其他操作将在编译时失败(错误的方法签名),否则将在运行时被吞下。
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?
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;
}
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;
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 ++流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!