Tuesday, December 08, 2009

Debug class implementation with templates

Here is the implementation of a debug reporting system in C++, with the same interface as cerr but with the plus of implementing a static debug level in your code.
template<int compiledDebugLevel>
class DebugCls {
  public:    /// Sends an object to the standard error.
    template<class T>
    DebugCls& operator<<(const T& a) const;
    /// Allows to use manipulators on the object.
    errorCls& operator<<(ostream& (*a)(ostream&));
    /// Allows to use the object as a function.
    DebugCls& operator()(const char* msg) const;
};

DebugCls<1> debug1; ///< Debug object for level 1.
DebugCls<4> debug4; ///< Debug object for level 4.
DebugCls<6> debug6; ///< Debug object for level 6.
DebugCls<10> debug10; ///< Debug object for level 10.

Reasonable limit for new neighbor requests which have fallen beyond the available memory for a person.
const int debugLevel = 0; ///< Chosen debug level for the current build.

template<int compiledDebugLevel>
template<class T>
DebugCls<compiledDebugLevel>& DebugCls<compiledDebugLevel>::operator<<(const T& a) const {
  if (compiledDebugLevel < debugLevel)
  cerr << a;
  return *this;
}

template<int compiledDebugLevel>

DebugCls<compiledDebugLevel>& DebugCls<compiledDebugLevel>::operator<<(ostream& (*a)(ostream&)) const {
  if (compiledDebugLevel < debugLevel)
  cerr << a;
  return *this;
}

template<int compiledDebugLevel>
DebugCls<compiledDebugLevel>& DebugCls<compiledDebugLevel>::operator()(const char* msg) const {
  if (compiledDebugLevel < debugLevel)
  cerr << "Program error: " << msg << "\n";
  return *this;
}
The functions have been written outline in this example so you get an idea of the required template nesting. However, these functions are short, so you might as well inline them.

No comments:

Post a Comment

Is your comment or question:

1. Constructive?
2. Interesting?
3. Short?

If not, please post it in your own blog.