tags:

views:

107

answers:

2

Possible Duplicate:
C/C++: How to make a variadic macro (variable number of arguments)

Just wondering if this is at all possible., so instead of how im currently handling logging and messages with multiple parameters im having to have a number of different macros for each case such as:

#define MSG(             msg                                    )
#define MSG1(            fmt, arg1                              )
#define MSG2(            fmt, arg1, arg2                        )
#define MSG3(            fmt, arg1, arg2, arg3                  )
#define MSG4(            fmt, arg1, arg2, arg3, arg4            )
#define MSG5(            fmt, arg1, arg2, arg3, arg4, arg5      )
#define MSG6(            fmt, arg1, arg2, arg3, arg4, arg5, arg6)

is there any way of defining just one macro that can accept any number of arguments?

thanks

+2  A: 

Well since @GMan didn't want to put that as an answer himself, have a look at variadic macros which are part of the C99 standard.

Your question is tagged C++ though. Variadic macros are not part of the C++ standard but they are supported by most compilers anyway: GCC and MSVC++ starting from MSVC2005.

Gregory Pakosz
since you're trying to define `MSG1(fmt, arg1) I bet you're wanting to use something like `printf`?
Gregory Pakosz
a number of things to be honest, all will be formatted strings, but will be outputting to bits of UI, log files and possibly message boxes.but yeah you are right this is C not C++, will give variadic macros a trythanks
Stowelly
while you're playing with variadic macros, here is a shameless plug to an answer I gave to another question http://stackoverflow.com/questions/1872220/is-it-possible-to-iterate-over-arguments-in-variadic-macros/1872506#1872506
Gregory Pakosz
Bah, after all this it seems va args are banned as part of our coding standard. i guess there isnt really any other way :(
Stowelly
limits are there to be pushed :D
Gregory Pakosz
I was informed about a clause in my contract that states "anyone who uses va args will be shot"
Stowelly
time to wear armor + helmet
Gregory Pakosz
+2  A: 

The following is the macro I use to generate exceptions - there is no need for variadic macros, which C++ does not currently support:

#define CSVTHROW( msg )         \
{                                 \
    std::ostringstream os;         \
    os << msg;                       \
    throw CSVED::Exception(os.str());   \
}                               \

In use it allows you to say things like:

CSVTHROW( "Problem caused by " << x << " being less than " << y );

You can easily replace the throw statement with a write to your log.

anon