C++ enable/disable debug messages of std::couts on the fly

Viewed 30829

Is there a way to define/undefine debug messages using std::cout whenever inside a program?

I am aware that there are such things such as #define, #ifndef, but I was thinking is there a cleaner way to having a variable say:

# debug ON

That prints all of my debug data (using std::cout). Consequently, we'll have code like this for debug:

#ifndef DEBUG
// do something useful
#endif

I find the above code cumbersome when you write 100s of debug code.

Thanks!

Carlo

9 Answers

I was looking for similar example and sharing my example below:

#include <iostream>
enum debug_option
{
    DEBUG_DISABLE,
    DEBUG_ENABLE
};

class debug
{
public:
    debug_option debug_state;

    debug() : debug_state(DEBUG_ENABLE) {} // constr
    debug(debug_option state) : debug_state(state) {} // constr

    template<typename T>
    debug & operator<< (T input)
    {
    if (this->debug_state == DEBUG_ENABLE)
        std::cout << input;
    return *this;
    }
};

int main()
{
    debug log, log_lev2(DEBUG_DISABLE);
    log << "print 1..\n" << 55 << " over\n";
    log.debug_state = DEBUG_DISABLE;
    log << "print 2..\n" << 3 << "over\n";
    log_lev2 << "print 3..\n" << 4 << "over\n";
    log_lev2.debug_state = DEBUG_ENABLE;
    log_lev2 << "print 5..\n";
    std::cout << "std::cout << print..\n";
    return 0;
}

Better suggestions are always welcome.

Related