gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 18:15:10 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com