Pietro M
Pietro M

Reputation: 1939

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!

Upvotes: 7

Views: 4148

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 477368

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;

Upvotes: 5

Mike Seymour
Mike Seymour

Reputation: 254631

// 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;
}

Upvotes: 12

Related Questions