c++ - how to forward variable number of arguments to another function? -


this question has answer here:

in application have lot of logs. accumulate errors logs in 1 place called errorslogger. i've implemented way:

static logger errorslogger;  ....  void logger::error(std::string format, ...) {     va_list arglist;     va_start(arglist, format);      if (this != &errorslogger) {         errorslogger.error(format, arglist);      // how forward parameters?     }      vfprintf(logfile, , format.c_str(), arglist);     fprintf(logfile, "\n");      fflush(logfile);     va_end( arglist ); } 

however code doesn't work expected errorslogger contains little bit strange strings - seems variable arguments not passed. how fix code valid?

the typical formulation of in c have 2 functions, 1 accepts ... , 1 accepts va_list (e.g., printf versus vprintf). in c++ it’s convenient overloads:

// public void logger::error(const std::string& format, ...) {     va_list args;     va_start(args, format);     error(format, args);     va_end(args); }  // private void logger::error(const std::string& format, va_list args) {     if (this != &errorslogger)         errorslogger.error(format, args);      vfprintf(logfile, format.c_str(), args);     fprintf(logfile, "\n");     fflush(logfile); } 

using c++11, possible directly variadic template. haven’t tested this, i’m pretty sure can forward arguments c-style variadic functions.

template<class... args> void logger::error(const std::string& format, args&&... args) {         if (this != &errorslogger)         errorslogger.error(format, std::forward<args>(args)...);      fprintf(logfile, format.c_str(), std::forward<args>(args)...);     fprintf(logfile, "\n");     fflush(logfile); } 

Comments

Popular posts from this blog

java - Jmockit String final length method mocking Issue -

asp.net - Razor Page Hosted on IIS 6 Fails Every Morning -

c++ - wxwidget compiling on windows command prompt -