C++ 可变函数语法

C++ variadic function syntax

在 C++03 标准中,[dcl.fct] p.2 指出:

The parameter-declaration-clause determines the arguments that can be specified, and their processing, when the func- tion is called. [ Note: the parameter-declaration-clause is used to convert the arguments specified on the function call; see5.2.2. —endnote]Iftheparameter-declaration-clauseisempty,thefunctiontakesnoarguments.Theparameter list (void) is equivalent to the empty parameter list. Except for this special case, void shall not be a parameter type (though types derived from void, such as void*, can). If the parameter-declaration-clause terminates with an ellipsis, the number of arguments shall be equal to or greater than the number of parameters that do not have a default argument. Where syntactically correct, “, ...” is synonymous with “...”.

parameter-declaration-clause 的语法允许它以 ..., ... 结尾。我找到 并且答案说最初语法只允许 ...,引入逗号变体 (, ...) 是为了与 C 兼容。

我的问题是为什么引用的段落说 "where syntactically correct"?考虑到 function parameter packspack expansions 不存在于 C++03 中,是否有任何情况 "syntactically incorrect" 将 ... 视为 , ... 的同义词?

谢谢。

根据我的理解,这只是意味着当您使用语法正确的 ,... 时,可以将其替换为 ... 例如:

  • int printf(const char*, ...); 是正确的语法,可以替换为 int printf(const char*...);

  • int printf(,...); 在语法上不正确并且不等同于 int printf(...);

您只需添加以下原型即可轻松尝试 C 代码:

  • void printf(...); --> 有效
  • void printf(,...); --> ‘,’标记前的预期主表达式

are there any cases where it would be "syntactically incorrect" to consider ... synonymous with , ...?

正如纪尧姆所说,"syntactically incorrect" 重写

foo(...)

作为

foo(, ...)

所以该子句只处理没有先验参数的极端情况,省略号可以用逗号分隔。