空流,我必须包括ostream吗? [英] Null stream, do I have to include ostream?
本文介绍了空流,我必须包括ostream吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在写一个记录器。如果禁用,这是定义LOG宏的代码:
I am writing a logger. If disabled, this is the code which defines the LOG macro:
#ifdef NO_LOG
#include <ostream>
struct nullstream : std::ostream {
nullstream() : std::ios(0), std::ostream(0) {}
};
static nullstream logstream;
#define LOG if(0) logstream
#endif
LOG << "Log message " << 123 << std::endl;
它可以正常工作。编译器应该完全删除与LOG宏相关的代码。
It works correctly. The compiler should completely remove the code related to the LOG macro.
但是,我想避免包含ostream并将logstream对象定义为真正的轻可能为空。
However I would like to avoid the inclusion of ostream and define the logstream object as something really "light", possibly null.
谢谢!
推荐答案
// We still need a forward declaration of 'ostream' in order to
// swallow templated manipulators such as 'endl'.
#include <iosfwd>
struct nullstream {};
// Swallow all types
template <typename T>
nullstream & operator<<(nullstream & s, T const &) {return s;}
// Swallow manipulator templates
nullstream & operator<<(nullstream & s, std::ostream &(std::ostream&)) {return s;}
static nullstream logstream;
#define LOG if(0) logstream
// Example (including "iostream" so we can test the behaviour with "endl").
#include <iostream>
int main()
{
LOG << "Log message " << 123 << std::endl;
}
这篇关于空流,我必须包括ostream吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文