Is there a way to create an ostream instance which basically doesn\'t do anything ?
For example :
std::ostream dummyStream(...);
dummyStream <<
For runtime-controllable redirection of log messages, a self-contained solution combining the ideas of john and Sjoerd:
class DebugStream {
private:
class NullStream : public std::ostream {
private:
class NullBuffer : public std::streambuf {
public:
int overflow(int c) override { return c; }
} buffer_;
public:
NullStream() : std::ostream(&buffer_) {}
} null_;
std::ostream &output_;
bool enabled_;
public:
DebugStream(std::ostream &output = std::cout) : output_(output), enabled_(false) {}
void enable(const bool enable) { enabled_ = enable; }
template std::ostream& operator<<(const T &arg) {
if (enabled_) return output_ << arg;
else return null_ << arg;
}
};
extern DebugStream debug_stream;
#define TRACE_ENABLE(x) debug_stream.enable(x)
#define TRACELN(x) debug_stream << x << std::endl
#define TRACE(x) debug_stream << x
Then you can do stuff like:
TRACELN("The value of x is " << x " and the value of y is " << y);
It would also be easy to just remove the trace statements from a release version completely with #define the trace macros to empty statements.
You still need to define debug_stream somewhere global, though.