我正在写一个记录器。如果禁用,则这是定义LOG宏的代码:
#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宏相关的代码。
但是我想避免包含ostream并将logstream对象定义为真正“轻”的东西,可能为null。
谢谢!
答案 0 :(得分:12)
// 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;
}
答案 1 :(得分:5)
为什么不从头开始实施整个事情:
struct nullstream { };
template <typename T>
nullstream & operator<<(nullstream & o, T const & x) { return o; }
static nullstream logstream;