asm*_*asm 5 c++ logging operator-keyword
我正在用c ++编写一个日志类.这个班是一个单身人士.我想以这样的方式添加日志:
Log::GetInstance() << "Error: " << err_code << ", in class foo";
Run Code Online (Sandbox Code Playgroud)
好吧,在Log对象中,我希望在最后一个参数出现时保存整行(",在本例中为"类foo").
如何检测最后一个<<参数?<< a << b << is_this_last << maybe_this_is << or_not.
我不使用任何结束标签.
Job*_*Job 17
您可以通过不使用单例来解决此问题.如果你做这样的函数:
Log log()
{
return Log();
}
Run Code Online (Sandbox Code Playgroud)
您可以像以前一样添加日志:
log() << "Error: " << err_code << ", in class foo";
Run Code Online (Sandbox Code Playgroud)
不同之处在于Log对象的析构函数在此行之后被调用.所以现在你有办法检测最后一个参数的处理时间.
您让 Log 在运算符 << 之后返回一个不同的对象。
template<typename T>
LogFindT operator<<(Log aLog, T const& data)
{
// Put stuff in log.
log.putStuffInLog(data);
// now return the object to detect the end of the statement.
return LogFindT(aLog);
}
struct LogFindT
{
LogFindT(Log& aLog) : TheLog(aLog) {}
Log& TheLog;
~LogFindT()
{
// Do stuff when this object is eventually destroyed
// at the end of the expression.
}
};
template<typename T>
LogFindT& operator<<(LogFindT& aLog, T const& data)
{
aLog.TheLog.putStuffInLog(data);
// Return a reference to the input so we can chain.
// The object is thus not destroyed until the end of the stream.
return aLog;
}
Run Code Online (Sandbox Code Playgroud)