Нулевой поток, нужно ли включать ostream? - PullRequest
7 голосов
/ 08 декабря 2011

Я пишу регистратор. Если отключено, это код, который определяет макрос 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 как нечто действительно «светлое», возможно, нулевое.

Спасибо!

Ответы [ 2 ]

12 голосов
/ 08 декабря 2011
// 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;
}
5 голосов
/ 08 декабря 2011

Почему бы не реализовать все это с нуля:

struct nullstream { };

template <typename T>
nullstream & operator<<(nullstream & o, T const & x) { return o; }

static nullstream logstream;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...