Variable argument list

Started by
4 comments, last by antareus 19 years, 5 months ago
how I can pass-throught variable argument list? I would like to do something like this:

void Log(const File& f,const std::string& msg,...)
{
    fprintf(f.GetFilePointer(),"\nLogged: "+msg,...);
}

So I could do something like this: Log(LogFile,"The object loaded have %d vertices.",num_vertex); Log(LogFile,"Error in line %d.",num_line); logfile: Logged: The object loaded have 1500 vertices. Logged: Error in line 321. thnx
Advertisement
va_list args;
va_start(args, msg);
vfprintf(f.GetFilePointer(), msg, args);
--God has paid us the intolerable compliment of loving us, in the deepest, most tragic, most inexorable sense.- C.S. Lewis
thnx very much
There are much better ways of doing it that unsafe variable argument lists though. Why not just overload operator<<()?

Enigma
The va_list method is inheritly:
1) NOT typesafe
2) UNDEFINED with user-defined objects passed by VALUE or REFERENCE (only builtin types and pointers)
3) "C with some features" rather than C++.

Prefer to use an overloading of operator<< instead, or Boost Format.

Example:

void Log( const File& file, const std::string & Message ){    fputs( Message.c_str() , file.GetFilePointer() );}//...Log( LogFile , str( format("The object loaded has %1% vertices.") % num_vertex ) );


This method is:
1) TYPESAFE. If num_vertex has it's type changed, the program will still run correctly.
2) DEFINED for user-types. If they overload operator<< they will work just fine.
3) Using boost, one of the awesomest librarys in existance.
Nothing wrong with using varargs for logging type functions. << is annoying to type. That is, the 'C++ way' isn't always so much better such that it is worthwhile to proselytize it.
--God has paid us the intolerable compliment of loving us, in the deepest, most tragic, most inexorable sense.- C.S. Lewis

This topic is closed to new replies.

Advertisement