简体   繁体   中英

c++ pass formatted string as argument to a function

OK, this really shouldn't be difficult, but after several attempts, I didn't find any solution.

How can one go about passing a formatted string to a function in 1 line? I want to have a simple method that I can use for logging/debugging purposes, something like this:

void debug(string s){
    if (DEBUG) cerr << s;
}

I would like to be able to send formatted strings to this function, something like this:

debug("reading %s" % fname);

My main goal is to put as much functionality in the debug method so I can make life somewhat easier whenever I want to write stuff to stderr.

printf solutions seem to need a lot of code for simple formatting and boost::format seems to return some vague type that cannot be easily used as an argument without always including some .str() stuff.

Am I too lazy to be a C++ programmer or is there a neat way of accomplishing this goal that I have yet to discover?

You can define a macro around fprintf using __VA_ARGS__:

#define DBGLOG(format, ...) if(DEBUG){ fprintf(stderr, "%s -- %d -- ", __FUNCTION__, __LINE__); fprintf(stderr, format, ##__VA_ARGS__);}

This will, if DEBUG is true, output the function name and line number followed by whatever you wanted to print.

ex:

DBGLOG("%d\n", some_integer);

This will prepend the function and line number to the integer value and print it out.

You can write a function that takes in the format and passes it to your other function:

void debug( std::string s )
{
    if (DEBUG) cerr << s; 
}

void debug( boost::format format )
{
     debug( format.str() );
}

The normal C++ solution here is a bit different: your debug function should return a wrapper around std::cerr (or any other output stream), something like:

class OStreamWrapper
{
    std::ostream* myStream;
public:
    OStreamWrapper( std::ostream* init ) : myStream( init ) {}
    template <typename T>
    OStreamWrapper& operator<<( T const& value )
    {
        if ( myStream != nullptr ) {
            *myStream << value;
        }
    }
};

OStreamWrapper
debug()
{
    return OStreamWrapper( DEBUG ? &std::cerr : nullptr );
}

You then use it:

debug() << "reading " << fname << '\n';

This has the added advantage that the actual conversions necessary to format the output aren't done unless debug is active.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM