Sign in to follow this  
Silly_con

Variable argument list

Recommended Posts

Silly_con    136
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

Share this post


Link to post
Share on other sites
Enigma    1410
There are much better ways of doing it that unsafe variable argument lists though. Why not just overload operator<<()?

Enigma

Share this post


Link to post
Share on other sites
MaulingMonkey    1730
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.

Share this post


Link to post
Share on other sites
antareus    576
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this