Click to See Complete Forum and Search --> : forwarding variable number of arguments


mistretzu
March 21st, 2003, 08:18 AM
I want to write a general method that will add entries to a log file.
My problem is that i don't know how to pass all the arguments from logEvent() method to CString::Format()

void CXServerLogFile::logEvent( UINT resID, char *first, ... )
{
CString strEvent;
strEvent.Format( resID, .... ); // what do i put here?
strEvent += "\n";
writeEvent( strEvent );
}

mistretzu
March 21st, 2003, 08:41 AM
I made some debuging through MFC to see how CString::Format() works, and i found the answer to my problem. Here is the code:

void CXServerLogFile::logEvent( UINT resID, ... )
{
CString strEvent;
CString strFormat;
strFormat.LoadString( resID );

va_list argList;
va_start( argList, resID );
strEvent.FormatV( strFormat, argList );
va_end( argList );

strEvent += "\n";
writeEvent( strEvent );
}

Graham
March 21st, 2003, 10:36 AM
Using va_args is very unsafe (you lose all your type-checking and parameter validation by the compiler). You would probably be better off looking for a solution that uses function overloading, rather than this extremely ugly method.

galathaea
March 21st, 2003, 12:42 PM
If all of the arguments are of the same type, I've always felt that this article (http://www.moderncppdesign.com/publications/inline_containers.html) by the Saint of the New Form (:)) worked fairly well. Otherwise, for different types, one should look into a type safe hetrogeneous container like a vector of boost::any, as found at www.boost.org and just pass one argument of this form...