You could use std::ostream
state flags to conditionally disable output. A corresponding use code look like this:
std::cout << log << "hello, ";
std::cout << "world\n";
The implementation which enables/disables output when using log
could be something like the code below: log
is actually constructing an objects which will disable the output if DEBUG
is not defined when inserted into a stream by setting the stream flag std::ios_base::failbit
. Its destructor will restore the stream state if the state got changed. Since a stream is used, you can also pass the stream object to a function and it will conditionally write output:
extern void f(std::ostream&);
f(std::cout << log);
Of course, the objects also work with other std::ostream
objects, not just std::cout
.
#ifndef SIMPLE_LOG
#define SIMPLE_LOG
#include <ostream>
class log_enabled
{
mutable std::ostream* stream;
mutable std::ios_base::iostate state;
bool logging;
public:
log_enabled(bool l)
: stream(0)
, state()
, logging(l) {
}
~log_enabled() {
if (stream) {
stream->clear(this->state);
}
}
std::ostream& setup(std::ostream& out) const {
if (!logging) {
this->stream = &out;
this->state = out.rdstate();
out.setstate(std::ios_base::failbit);
}
return out;
}
};
std::ostream& operator<< (std::ostream& out, log_enabled const& log) {
return log.setup(out);
}
# ifdef DEBUG
# define log log_enabled(true)
# else
# define log log_enabled(false)
# endif
#endif