简体   繁体   中英

C++ variadic function syntax

In the C++03 standard, [dcl.fct] p.2 states that:

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 “...” .

The grammar for a parameter-declaration-clause allows it to end in either ... or , ... . I found this question and the answers said that initially the grammar allowed only ... , and the comma variant ( , ... ) was introduced for compatibility with C.

My question is why does the quoted paragraph say "where syntactically correct"? Considering that function parameter packs or pack expansions were not present in C++03, are there any cases where it would be "syntactically incorrect" to consider ... synonymous with , ... ?

Thank you.

for my understanding, it just mean that when you use ,... with a correct syntax, then it can be replaced by ... for instance :

  • int printf(const char*, ...); is a correct syntax and can be replaced by int printf(const char*...);

  • int printf(,...); is not syntactically correct and is not equivalent to int printf(...);

You can easily try in a C code by just adding the following prototypes:

  • void printf(...); --> works
  • void printf(,...); --> expected primary-expression before ',' token

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

Exactly as Guillaume says, it would be "syntactically incorrect" to rewrite

foo(...)

as

foo(, ...)

so that clause just handles the corner case where there is no prior parameter from which the ellipsis can be separated by a comma.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM