Reputation: 1025
Is there any way (built-in or a code pattern) to ensure that a variadic function is passed the correct number of parameters? (This will be included as part of an API obviously, I can check my own internal code.)
I was considering requiring a UN32 Magic Number to be the last argument passed and check that for validity in the variadic function. Does anyone have any thoughts on that?
Upvotes: 3
Views: 1326
Reputation: 19514
You could use the PP_NARG macro to add a count semi-automatically.
int myfunc (int count, ...);
#define MYFUNC(...) myfunc(PP_NARG(__VA_ARGS__), __VA_ARGS__)
MYFUNC(a,b,c,d);
MYFUNC(a,b,c,d,e,f,g);
gcc -E produces:
int myfunc (int count, ...);
myfunc(4, a,b,c,d);
myfunc(7, a,b,c,d,e,f,g);
Upvotes: 4
Reputation: 3442
Couldn't you use the variadic template feature of C++0x applied to a function? This would generate a vararg function that is type-safe .
See this link with it's type-safe printf implementation using a variadic templated function
http://www2.research.att.com/~bs/C++0xFAQ.html#variadic-templates
Upvotes: 2
Reputation: 8924
No. Not possible.
Variadic breaks type-safety in a way that cannot be fixed.
If you want type-safety back, then consider breaking variadic function into several typesafe member function of a [small] class that holds the shared state between their calls.
This is always possible, even if multiple calls might look awkward compared to single variadic call.
Shared state is probably why you wanted variadic function in the first place.
Take iostream vs printf as example.
Upvotes: 1
Reputation: 69047
It depends on what you mean by "ensure that a variadic function is passed the correct number of parameters"...
Passing a UN32 Magic Number as last argument will allow you to determine where the list of arguments ends, so their overall number. So, by counting how many arguments you have found before UN32, you know how many arguments you have and your function should know whether is it enough. Don't know if it is ok for you to determine this at run-time (it could be too late)...
Anyway, usually variadic functions have a fixed argument list portion representing the mandatory arguments (at least one); so possibly this should be the way for you to ensure that the function gets the correct number of arguments...
Upvotes: 1
Reputation: 20093
There is no definitive way in C or C++ to ensure that the correct number of arguments have been passed to a variadic function. Even requiring a signature is not guaranteed to work as it may clash with the value of a valid argument. You will probably be much better off passing a vector<> as the element count retrieved is accurate.
Upvotes: 3
Reputation: 5423
va_*
macros just pop the variables from the local stack, so you have to trust the user. passing an array/size tuple could be safer, I think.
Upvotes: 4