函数调用语法

Function Call Syntax?

本文关键字:语法 函数调用      更新时间:2023-10-16

阅读" c++模板:完整指南"第22.5.3节

我对作者使用函数指针的语法感到困惑。我相信这种语法被称为"函数调用语法"?我觉得我在这里错过了什么…?我注释了有问题的代码部分。

template<typename F>
void my_sort(.., F cmp = F())
{
  ..
  if (cmp(x,y)) {..}
  ..
}
//*** WHAT IS THIS SYNTAX? ***
bool my_criterion()(T const& x, T const& y);
// call function with function pointer passed as value argument
my_sort(..., my_criterion);

我把所有的…并将my_criterion()中的T替换为int,但仍然无法编译。

他第一次提到这个语法是在它之前的一节:

"如前所述,这种函子规范技术的优点是,也可以将普通函数指针作为参数传递。例如:

bool my_criterion () (T const& x, T const& y);

我试图编译基于摘录的书的代码:

template<typename F>
void mySort(F cmp)
{
    std::cout << "mySort(F cmp)" << std::endl;
}
bool myCriterion()(int x, int y);

*错误C2091:函数返回函数(引用myCriterion)

我猜这是书中的一个打字错误。引自书中:

如前所述,这种函子规范技术的优点是也可以传递普通函数指针作为参数。例如:
bool my_criterion () (T const& x, T const& y); 
// call function with function object 
my_sort (… , my_criterion);

作者显然试图声明一个"普通函数"。函数名后面的括号不应该在那里

我的c++有点生疏,但谷歌一下发现了:函数指针教程

我想你缺少的是一个叫做Functor的类:

下面是一个小例子。

#include <iostream>
#include <string>
#include <sstream>

struct foobar {
  void operator()(int x, int y) {
    std::cout << x << y << std::endl;
  }
};
int main () {
  foobar()(10,20);
  return 0;
}