Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Passing std::ostream to a function

I thought of a small debug inline function in C++:

void inline debug( int debug_level, ostream& out ) {
    if ( debug_level <= verbosity ) {
        out.flush();
    }
    else {
        ostream tmp;
        tmp << out;
    }
}

This is an example of how I wanted to use it:

_debug( 7, cout << "Something something" << someint << endl );

However it does not work in the way I planned - I wanted it to print the message only if the verbosity level is higher or equal then the debug level passed to function, but it seems it prints everytime regardless of the debug level, so data stays in the cout buffer. By now I think this function's not the best idea I've had lately, but still I want to know if there's a way to clear the buffer associated with cout, cerr etc. Is it possible to get this kind of function to work properly?

like image 717
zbigh Avatar asked Oct 28 '25 00:10

zbigh


1 Answers

Either using a macro as shown above, or like this:

struct nullstream : ostream {
    nullstream() : ostream(0) { }
};

ostream& dout(int debug_level, ostream& out = cerr) {
    static nullstream dummy;
    return debug_level <= verbosity ? dummy : out;
}

// …

dout(level) << "foo" << endl;
dout(level, cout) << "IMPORTANT" << endl;

(Using endl also triggers flushing, no need to flush manually!)

like image 142
Konrad Rudolph Avatar answered Oct 29 '25 17:10

Konrad Rudolph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!