【发布时间】:2021-08-21 12:34:09
【问题描述】:
如何使用(在类中包装 ostream 并模板化
我想为记录器使用 SEVERITY 级别,每个级别可以采用任意数量的 msg/ 元素
这个类接受对象中任意数量的元素,但我也需要类中的每个函数 例如:
ClassName ClassObject(&std::cout)
ClassObject.info() << "test msg" << 5 << 10 << endl;
这是我的课
class logger {
private:
ostream * str;
public:
logger( ostream* str_v) : str(str_v) {}
template <class T>
logger& operator<<(T&& x) {
*str << std::forward<T>(x);
return *this;
}
logger& operator<<(ostream& (*manip)(ostream&)) {
*str << manip;
return *this;
}
void info(){
cout <<"hello world"<<endl;
}
};
int main(){
logger l(&std::cout);
l << 5 << std::string(" test")<<endl;
//I want to use info like that
l.info() << "print anything" << 5 << endl;
return 0;
}
【问题讨论】:
-
让
info()写入*str并返回对*this的引用? -
对了,为什么不用引用而不是指向流的指针呢?
-
回到手头的问题,我个人的做法是拥有第二个帮助程序类,它由严重性/级别函数返回。这个辅助类具有流重载功能,它还写入一个换行符并在销毁时刷新流。然后保证输出以换行符结束并实际写入。无需在日志“调用”中使用
endl。 -
@Someprogrammerdude 抱歉,但我是 C++ 新手,你能给我一些例子更清楚吗
-
您能否详细说明写入不同日志级别的预期效果?假设有一个
debug日志级别与log.debug() << x << endl;相比,log.info() << x << endl;的预期结果是什么?您能否将代码中main函数的所需输出添加到问题中?
标签: c++ oop logging wrapper ostream