2011-12-08 10 views
7

Piszę logger. Jeśli wyłączone, jest to kod definiujący makro LOG:Null stream, czy muszę dołączyć ostream?

#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; 

Działa poprawnie. Kompilator powinien całkowicie usunąć kod związany z makrem LOG.

Chciałbym jednak uniknąć włączenia ostream i zdefiniować obiekt logstream jako coś naprawdę "lekkiego", prawdopodobnie zerowego.

Dziękujemy!

Odpowiedz

12
// 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; 
} 
+0

Działa, ale czy można uniknąć włączenia iostream? Np. Czy możliwe jest użycie czegoś innego zamiast std :: endl? –

+0

@Pietro: to jest potrzebne tylko dla przykładu, dla 'std :: endl'. 'nullstream' samo nie potrzebuje tego, tylko' '(deklaracje forward typu' '). –

+0

@Pietro Często możliwe jest użycie '\ n' zamiast std :: endl. – UncleBens

5

Dlaczego nie wdrożyć całą rzecz od podstaw:

struct nullstream { }; 

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

static nullstream logstream; 
+2

To powinno być '' nullstream' zamiast std :: ostream'? – sth

+2

Masz na myśli 'nullstream & operator << (nullstream i o, T const i x)'? I nie będzie działać z 'endl'. – fefe

+0

@fefe: masz rację; endl wydaje się teraz być jedynym problemem. Czy możliwe jest zakończenie strumienia w inny sposób. Naprawdę chciałbym uniknąć włączenia ostream, jeśli nie potrzebuję rejestrowania ... –

Powiązane problemy