问题描述
我正在考虑制作一个日志类,其中包含 Info、Error 等成员,可以配置输出到控制台、文件或无处.
I'm looking at making a logging class which has members like Info, Error etc that can configurably output to console, file, or to nowhere.
为了效率,我想避免格式化将被丢弃的消息(即不在详细模式下运行时的信息消息)的开销.如果我实现了一个无处输出的自定义 std::streambuf,我想 std::ostream 层仍将执行所有格式设置.任何人都可以提出一种拥有真正空"的 std::ostream 的方法,避免对使用 <<
传递给它的参数做任何工作?
For efficiency, I would like to avoid the overhead of formatting messages that are going to be thrown away (ie info messages when not running in a verbose mode). If I implement a custom std::streambuf that outputs to nowhere, I imagine that the std::ostream layer will still do all the formatting. Can anyone suggest a way to have a truly "null" std::ostream that avoids doing any work at all on the parameters passed to it with <<
?
推荐答案
为了防止 operator<<()
调用进行格式化,您应该在编译时知道流类型.这可以通过宏或模板来完成.
To prevent the operator<<()
invocations from doing formatting, you should know the streamtype at compile-time. This can be done either with macros or with templates.
我的模板解决方案如下.
My template solution follows.
class NullStream {
public:
void setFile() { /* no-op */ }
template<typename TPrintable>
NullStream& operator<<(TPrintable const&)
{ return *this; } /* no-op */
}
template<class TErrorStream> // add TInfoStream etc
class Logger {
public:
TErrorStream& errorStream() {
return m_errorStream;
}
private:
TErrorStream m_errorStream;
};
//usage
int main() {
Logger<std::ofstream> normal_logger; // does real output
normal_logger.errorStream().open("out.txt");
normal_logger.errorStream() << "My age is " << 19;
Logger<NullStream> null_logger; // does zero output with zero overhead
null_logger.errorStream().open("out.txt"); // no-op
null_logger.errorStream() << "My age is " << 19; // no-op
}
由于您必须在编译时执行此操作,因此当然非常不灵活.
Since you have to do this at compile-time, it is of course quite inflexible.
例如,您无法在运行时从配置文件中决定日志级别.
For example, you cannot decide the logging level at runtime from a configuration file.
这篇关于实现无操作 std::ostream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!