空流,我必须包含ostream吗?
Null stream, do I have to include ostream?
我正在写一个日志记录器。如果禁用,下面是定义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;
相关文章:
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 编译包含字符串的代码时遇到问题
- c++库的公共头文件中应该包含什么
- 将包含C样式数组的对象初始化为成员变量(C++)
- 是否需要删除包含对象的"pair"?
- ostream过载时的缓冲区冲洗
- 函数何时会在c++中包含stack_Unwind_Resume调用
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 使用mongocxx驱动程序时包含头文件问题
- 如何在h文件中包含.o对象文件
- 在混合代码库中将C转换为C++时出现许多包含错误
- 需要从 istream 和 ostream 派生 iostream
- VS2017,C++包含目录与附加包含目录,子文件夹包含失败-但为什么
- cmath抛出错误C2062、C2059、C2143和C2447.cmath包含在矢量文件中
- 为什么您需要C++头文件的包含保护
- 无法在UE4中包含BP类到CPP类
- g++ 说函数不存在,即使包含正确的标头
- C++创建一个标头,其中包含用于重载 ostream 的模板
- 空流,我必须包含ostream吗?