Default arguments and variadic functions

2019-06-15 22:11发布

Is there any way to specify a default parameter in a variadic function?(Applies to templates also)

4条回答
Juvenile、少年°
2楼-- · 2019-06-15 22:12

No there is not way of doing that.

查看更多
Rolldiameter
3楼-- · 2019-06-15 22:16

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.

查看更多
成全新的幸福
4楼-- · 2019-06-15 22:24

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.

查看更多
倾城 Initia
5楼-- · 2019-06-15 22:36

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.,

查看更多
登录 后发表回答