Although I currently don't use it much, I fancy myself a bit of a C++ programmer. Over the years, I've accumulated a number of neat C++ coding tricks. For example, while in graduate school, I met Jeff Squyres who taught me a neat little C++ technique that I have used often since then. Jeff's trick is a low overhead C++ debugging stream. The real beauty is that all the debug statements can be compiled out without changing the source code:
// Author: Jeremy Faller // Copyright (c) 2007 Digital Sweetener, Inc. // // This software is distributed under the MIT license. // http://www.opensource.org/licenses/mit-license.php #if !defined(DEBUGSTREAM_H_) #define DEBUGSTREAM_H_ #include <iostream> class DebugStream { std::ostream &mStream; bool mOn; public: DebugStream(std::ostream &str, bool isOn = true) : mStream(str) , mOn(isOn) { } template <class T> inline DebugStream& operator<<(const T &inVal) { #if defined(DEBUG_ON_) if (mOn) mStream << inVal; #endif return *this; } inline DebugStream& operator<<(std::ostream& (*inVal)(std::ostream&)) { #if defined(DEBUG_ON_) if (mOn) mStream << inVal; #endif return *this; } void Reset() { mOn = true; } bool On() const { return mOn; } bool& On() { return mOn; } }; extern DebugStream debug; #endif // DEBUGSTREAM_H_
And using it is simple enough:
#include "debugstream.h" DebugStream debug(std::cout); int main() { debug << "Debug" << std::endl; debug.On() = false; debug << "This line will not print" << std::endl; return 0; }
While using DebugStream, please keep in mind that although it is threadsafe, unexpected results can occur when twiddling the On() variable.
Post a Comment