c++ - 空流,我必须包括 ostream 吗?

标签 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。

谢谢!

最佳答案

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

关于c++ - 空流,我必须包括 ostream 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8433302/

相关文章:

c - 堆栈对齐如何工作?

php - 148 是不是包含的文件太多

video - 添加对自定义视频输入硬件的 QuickTime 支持

java - 带有 Swift 的 RESTful/JAX-RS?

c++ - 是否有可以解析 C++ 的优秀 Python 库?

c++ - 在未安装 Qt 的计算机上运行 Qt 应用程序。 QCamera 看不到可用的设备

c++ - 如何在现有的 json11 对象上附加属性值对(c++)?

c++ - 从基类指针获取派生成员

iphone - 绘图线的优化,CAShapeLayer 的可能替代品

dart - 如何将最新的流图组合成值图?