我正在写一个记录器。如果禁用,这是定义 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)