本文介绍了实现no-op std :: ostream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



为了提高效率,我建议使用一个日志类,该类包含Info,Error等可以配置输出到控制台,文件或无处不在的成员。 ,我想避免格式化将被抛弃的消息(即不在详细模式下运行时的信息消息)的开销。如果我实现一个自定义std :: streambuf输出到无处,我想std :: ostream层仍然会做所有的格式化。任何人都可以建议一个真正的nullstd :: ostream,避免做任何工作的参数传递给它与< ?

感谢。

解决方案

为了防止 ;<()执行格式化的调用,你应该知道编译时的streamtype。这可以通过宏或模板来完成。



我的模板解决方案如下。

 code> class NullStream {
public:
void setFile(){/ * no-op * /}
template< typename TPrintable>
NullStream& <<<(TPrintable const&)
{/ * no-op * /}
}

template< class TErrorStream> // add TInfoStream etc
class Logger {
public:
TErrorStream& errorStream(){
return m_errorStream;
}

private:
TErrorStream m_errorStream;
};

//用法
int main(){
Logger< std :: ofstream> normal_logger; // does real output
normal_logger.errorStream()。open(out.txt);
normal_logger.errorStream()<< 我的年龄是< 19;

Logger< NullStream> null_logger; //零输出零开销
null_logger.errorStream()。open(out.txt); // no-op
null_logger.errorStream()<< 我的年龄是< 19; // no-op
}

由于在编译时必须这样做,



例如,您无法从配置文件中确定运行时的日志记录级别。


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.

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 <<?

Thanks.

解决方案

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&)
    { /* 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.

这篇关于实现no-op std :: ostream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 03:56