备用函数 syntax/function 原型?

Alternate function syntax/function prototypes?

我一直在 C++ 中使用函数指针,我一直将它们声明为 void (*function)(void)。这就是我最初在教程和 how tutorials still teach it.

中看到的方式

但是今天,我在阅读维基百科关于高阶函数的文章时发现了一个使用替代语法的示例,其中 * 和函数指针 variable/type 名称周围的括号不存在, 如 here.

所示

我测试了 void function(void) 形式是否适用于变量、参数和 typedef。它不适用于变量,但它适用于参数和类型定义,没有明显的变化,实际上可以与标准函数指针语法互换。

我进一步挖掘,发现 that seems to imply it's the syntax for a 'function prototype' rather than a function pointer. However wikipedia's explanation of function prototypes 听起来很像预声明函数。

对于我的问题范围太广,我深表歉意,但是 这个语法到底是什么?

不,它们不一样。数组和指针不一样只是因为您可以将 int A[] 写为参数。具体规则可以参考n4567标准草案:

§8.3.5/5 ... After determining the type of each parameter, any parameter of type "array of T" or of function type T is adjusted to be "pointer to T". ...

后面更明确:

§13.2/3 ...

  • Parameter declarations that differ only in that one is a function type and the other is a pointer to the same function type are equivalent. That is, the function type is adjusted to become a pointer to function type (8.3.5). [ Example:

     void h(int());
     void h(int (*)());     // redeclaration of h(int())
     void h(int x()) { }    // definition of h(int())
     void h(int (*x)()) { } // ill-formed: redefinition of h(int())
    

    end example ] ...

该规则也适用于其他地方(不是完整列表):

  • non-type 模板参数
  • 模板参数推导
  • 异常处理程序