空流,我必须包括ostream吗?

时间:2011-12-08 15:24:11

标签: c++ optimization stream null

我正在写一个记录器。如果禁用,则这是定义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。

谢谢!

2 个答案:

答案 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;