默认参数和可变参数函数
有没有办法在可变参数函数中指定默认参数?(也适用于模板)
Is there any way to specify a default parameter in a variadic function?(Applies to templates also)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 C++ 中,您可以将可变参数函数替换为基于命名参数习惯用法的函数。
请参阅 C++ 常见问题解答项目 10.20 什么是“命名参数习惯用法”?。
这为您提供了默认功能和方便的记号。
干杯&呵呵,
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.,
为什么你需要可变参数和默认参数?
例如,
可以接收0-3个具有默认值的参数,并且
可以接收任意数量的参数。在函数内部,您可以检查是否缺少参数并根据需要填写默认值。
Why would you need both variadic and default params?
For example,
can receive 0-3 parameters with default values, and
can reveive any number of parameters. Inside the function, you can check for missing parameters and fill in the default values as required.
首先是 C++ 答案。
默认参数是您知道函数应该并且将会看到所提供的参数。因此,您应该明确命名这些参数,然后可以提供默认参数。这将是您的函数的“简短”版本。
如果除了后面的这些默认参数之外,您还想拥有 va_arg 参数列表,只需使用第二个版本来重载您的函数即可。对于那个“长”版本,无论如何,您都必须提供所有参数,因此在这里使用默认参数是没有意义的。
现在是 C 答案
可能您没有研究这样的事情,但是使用 C99 的
va_arg
宏 功能,可以定义 C 中函数的默认参数。宏语法比 C++ 更宽松,因为您还可以在函数调用中间省略参数,而不仅仅是在最后。因此,如果您声明了类似的函数,并为位置 2 和 3 指定了默认参数,那么您可以将其称为 因此,
从这个意义上说,在 C 中,可以执行您所要求的操作。我个人肯定会犹豫是否要这么做。
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 likeand specified default arguments for positions 2 and 3, say, you could call it as
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.