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

I thought of a small built-in debugging 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 doesn’t work as I planned - I wanted it to print a message only if the verbosity level is higher or equal and the debug level is passed to the function, but it seems to print every time, regardless of the debug level, therefore, the data remains in the cout buffer. At the moment, I think this function is not the best idea I have had recently, but still I want to know if there is a way to clear the buffer related to cout, cerr, etc. Is it possible for this function to function correctly?

+3
source share
4

, , :

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;

( endl , !)

+6

, /. ( - ):

#define LOG(svrty, out, msg)\
do {\
  if (svrty >= debug_level) out << msg;\
} while(0)

, . , , .

+2

, . , , , , , , :

#define DOUT( level, expr )   \
   if ( level >= verbosity )  {     \
      expr << endl;          \
  }

:

 DOUT( 42, cout << "The value is " << something );

, do/while - , .

+2
source

Can I customize the debug runtime? If you cannot use templates and template specialization:

template <int DebugLevel, int Verbosity>
ostream &debug(ostream &out);

template<>
ostream &debug<7, 5>(ostream &out) { /* do stuff */ }

Thus, if you do not want to output anything, simply return the dummy flow, as Conrad Rudolph suggested.

0
source

Source: https://habr.com/ru/post/1731185/


All Articles