I have some code that is sprinkled with constructs like this
if(debug) {
Output << "f1: " << f1() << "\n";
}
Now what I want to do is write a stream class Debug
where I could write it like this
Debug << "f1: " << f1() << "\n";
If some global flag is set then this would generate output, otherwise not.
Now: this can be quite easily done by making Debug
return a stream that goes to /dev/null
which would swallow the output. The problem is that f1()
still gets evaluated (and 'rendered' into a textual representation which might be even more expensive) which might be quite bad for the performance.
Now my question: is there any trick that allows the skipping of the 'evaluation' of
"f1: " << f1() << "\n"
completely if Debug
decides that no output should be done? Similar to the short circuiting that C++ does for f() && g()
where g()
is not evaluated if f()
is false
(I seriously considered writing a stream class that uses &&
as the output operator but from what I read short-circuiting is not done for overloaded operator&&
)
What you can do is define this macro:
#define Debug_Stream \
if(!debug); else Output
This would make this:
Debug_Stream << "f1: " << f1() << "\n";
become equivalent to this:
if(debug) {
Output << "f1: " << f1() << "\n";
}
But literally (plus whitespace for readability)
if(!debug);
else
Output << "f1: " << f1() << "\n";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With