结构的原型函数

Prototyped function of structs

今天遇到了this段代码:

int main() {
  struct Foo {};
  struct Bar {};

  Foo(b)(int (Bar*c)); // ?

  return 0;
}

我完全不知道发生了什么。我的编译器 (VC14) 警告我未使用的原型函数?

这一行是干什么的(声明一个函数:什么名字,什么参数,return类型?怎么调用?)

Foo(b)(int (Bar*c));

在此先感谢您对我的帮助!

这声明了一个名为 b 的函数,该函数:

  • int (Bar*c)为参数;
  • returns Foo.

参数的类型 int (Bar*c) 是一个指向函数的指针,该函数采用指向 Bar 和 returns 和 int 的指针。这里,c 是参数的名称,可以省略:int (Bar*).

以下是调用 b 的方法:

int main() {
  struct Foo {};
  struct Bar {};

  Foo(b)(int (Bar* c)); // the prototype in question

  int func(Bar*);       // a function defined elsewhere
  Foo result = b(func);

  return 0;
}

这不是有效的 C(因为名称 FooBar 不涉及类型;您必须使用 struct 关键字或使用 typedef)。

在 C++ 中,这是一个令人惊讶但有效的声明。它将 b 声明为返回 Foo 并采用“(指向)函数返回 int 并采用指向 Bar 的指针类型的参数”类型参数的函数。

为了生成可读的类型声明,我编写了以下代码:

#include <typeinfo>
#include <iostream>


int main() {
    struct Foo {};
    struct Bar {};

    Foo(b)(int (Bar*c));
    std::cout << typeid(b).name();

    return 0;
}

然后我编译了它并通过 c++filt 过滤了它的输出。 结果是:

main::Foo (int (*)(main::Bar*))

完全清楚了。

实际上,我的编译器 (Clang 3.5) 给了我以下警告:

warning: parentheses were disambiguated as a function declaration [-Wvexing-parse]

这更重要,因为你正在处理 Most vexing parse

以下声明:

Foo(b)(int (Bar*c));

声明一个 b 函数指针 指向一个 returns Foo 的函数,并将 [=30] 的函数作为参数=] int 并将指针指向 Bar 作为参数(例如:int (Bar*c))。

您的编译器可能认为这是一个函数原型,因此发出警告。