Your questions actually appeals to two answers. You want to do the universal logging function, that works like printf but can be fully customise. So you need:
- macro taking a variable number of arguments
- function taking a variable number of arguments
Here is your code example adatapted:
#include <stdio.h>
#include <stdarg.h>
class CLogClass
{
public:
static void DoLogWithFileLineInfo( const char * fmt, ... )
{
va_list ap;
va_start( ap, fmt );
vfprintf( stderr, fmt, ap );
va_end( ap );
}
};
#define MYLOG(format, ...) CLogClass::DoLogWithFileLineInfo("%s:%d " format , __FILE__, __LINE__, __VA_ARGS__)
int main()
{
MYLOG("Hello world!\n", 3); // you need at least format + one argument to your macro
MYLOG("%s\n", "Hello world!");
MYLOG("%s %d\n", "Hello world!", 3);
}
Variadic macros have been introduced in C99, so it will work on compilers supporting C99 or C++0x . I tested it successfully with gcc 3.4.2 and Visual Studio 2005.
Variadic arguments to functions have been there forever so no worry about compability here.
It's probably possible to do it with some template meta-programmaing but I don't see the interest of it given the simplicity of the code above.
As a last note, why use a static method in an empty class instead of a function ?