Default arguments and variadic functions
Is there any way to specify a default parameter in a variadic function?(Appl开发者_如何学运维ies to templates also)
In C++ you can replace the variadic function with one based on the Named Parameter Idiom.
See the C++ FAQ item 10.20 What is the "Named Parameter Idiom"?.
That gives you default functionality & convenient notation.
Cheers & hth.,
Why would you need both variadic and default params?
For example,
myFunc(int a=5, int b=5, int c=5);
can receive 0-3 parameters with default values, and
myFunc(...)
can reveive any number of parameters. Inside the function, you can check for missing parameters and fill in the default values as required.
First a C++ answer.
A default parameter is a parameter for which you will know that the function should and will see as provided. So you should definitively name these parameters and then may provide default arguments. This would be a "short" version of your function.
If in addition to these default arguments behind you want to have the possibility of having a va_arg
argument list just overload your function with a second version that does exactly this. For that "long" version you have to provide all arguments anyhow, so there would be no sense in having default arguments, here.
Now a C answer
Probably you were not looking into such a thing, but with the va_arg
macro features of C99 it is possible to define default arguments for functions in C, too. The macro syntax then is more permissive than it is for C++ in that you may also omit arguments in the middle of a function call, not only at the end. So if you would have declared your function something like
int toto(int a, ...)
and specified default arguments for positions 2 and 3, say, you could call it as
toto(4,5,,,37);
So in this sense in C it is possible to do what you asked for. I personally would certainly hesitate to do this.
No there is not way of doing that.
精彩评论