默认参数和可变参数函数

发布于 2024-10-01 06:03:45 字数 35 浏览 0 评论 0原文

有没有办法在可变参数函数中指定默认参数?(也适用于模板)

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

感情废物 2024-10-08 06:03:45

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

为什么你需要可变参数和默认参数?

例如,

myFunc(int a=5, int b=5, int c=5);

可以接收0-3个具有默认值的参数,并且

myFunc(...)

可以接收任意数量的参数。在函数内部,您可以检查是否缺少参数并根据需要填写默认值。

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.

2024-10-08 06:03:45

首先是 C++ 答案。

默认参数是您知道函数应该并且将会看到所提供的参数。因此,您应该明确命名这些参数,然后可以提供默认参数。这将是您的函数的“简短”版本。

如果除了后面的这些默认参数之外,您还想拥有 va_arg 参数列表,只需使用第二个版本来重载您的函数即可。对于那个“长”版本,无论如何,您都必须提供所有参数,因此在这里使用默认参数是没有意义的。

现在是 C 答案

可能您没有研究这样的事情,但是使用 C99 的 va_arg 功能,可以定义 C 中函数的默认参数。宏语法比 C++ 更宽松,因为您还可以在函数调用中间省略参数,而不仅仅是在最后。因此,如果您声明了类似的函数

int toto(int a, ...)

,并为位置 2 和 3 指定了默认参数,那么您可以将其称为 因此,

toto(4,5,,,37);

从这个意义上说,在 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 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.

清醇 2024-10-08 06:03:45

不,没有办法做到这一点。

No there is not way of doing that.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文