Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null stream, do I have to include ostream?

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!

like image 906
Pietro M Avatar asked Dec 08 '11 15:12

Pietro M


2 Answers

// 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;
}
like image 134
Mike Seymour Avatar answered Nov 10 '22 01:11

Mike Seymour


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;
like image 28
Kerrek SB Avatar answered Nov 10 '22 00:11

Kerrek SB