函数调用语法
Function Call Syntax?
阅读" 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;
}
相关文章:
- 函数调用中参数的顺序重要吗
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 变量没有改变?通过向量的函数调用
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 模板函数调用
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 析构函数调用
- 成员函数调用和C++对象模型
- 使用共享指针的函数调用,其对象应为 const
- C++:编译时检查匹配的函数调用对?
- 函数调用C++中的参数太少
- 需要"模板<>"语法 --> 通过函数调用类模板
- 压缩C++函数调用语法
- 奇怪的类似函数调用的语法
- 如何用C++兼容的语法转换C函数调用
- 显式复制构造函数调用语法
- 函数调用语法
- 奇怪的c++语法:函数调用之前的类型定义