I am writing a logger. If disabled, this is the code which defines the LOG macro:
#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;
It works correctly. The compiler should completely remove the code related to the LOG macro.
However I would like to avoid the inclusion of ostream and define the logstream object as something really "light", possibly null.
Thank you!
// 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;
}
Why not implement the entire thing from scratch:
struct nullstream { };
template <typename T>
nullstream & operator<<(nullstream & o, T const & x) { return o; }
static nullstream logstream;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With