我工作的公司有一个 Logger 类,我们用它来安排从多个线程到窗口的打印输出。它使用 printf 样式的格式,我正在尝试创建一个包装器以使其表现得像 cout。它几乎可以工作,我可以像这样调用包装器类:
wlog->info() << "hello: " << 1;
Run Code Online (Sandbox Code Playgroud)
它通过调用返回的帮助类的析构函数在链的末尾刷新wlog->info()
(它与 RAII 概念非常相似)。
但是,C++ 会发出警告,因为wlog->info()
返回的是右值,并且会出现警告,因为operator<<
重载需要左值引用。是否有解决此警告的方法,或者无需求助于特殊的行尾函数/字符/事物即可检测 << 链末尾的替代方法?
在下面编辑:抱歉花了这么长时间发布这篇文章,周末忙于圣诞节准备:) 我无法显示 Logger 类本身的代码,但它的行为与 printf 大致相同。调用 log->info("Hello: %d", 22); 将打印“信息 - 你好 22”。
logger_wrapper.h
#include<sstream>
#include<iomanip>
#include "logger/logger.h"
namespace logger {
// helper class // can't be a nested class (i think). need to be able to return it
class LoggerHelper {
private:
Logger* log;
std::stringstream ss; // using stringstream for auto-string conversion
int level; …
Run Code Online (Sandbox Code Playgroud) c++ ×1