空流,我必须包含ostream吗?

Null stream, do I have to include ostream?

本文关键字:ostream 包含 空流      更新时间:2023-10-16

我正在写一个日志记录器。如果禁用,下面是定义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对象定义为真正"轻"的东西,可能为空。

谢谢!

// 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;
}

为什么不从头开始实现整个东西呢:

struct nullstream { };
template <typename T>
nullstream & operator<<(nullstream & o, T const & x) { return o; }
static nullstream logstream;