函数调用语法?
阅读“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);
*error C2091: function returns function (参考myCriterion)
Reading "C++ Templates: The Complete Guide" Section 22.5.3
I'm confused over the syntax the author uses for function pointers. I believe this syntax is called the "Function Call Syntax"? I feel like I am missing something here..? I commented the section of the code in question.
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);
I replaced all the ..'s with appropriate values and replaced the T to an int in my_criterion() and it still won't compile.
He first mentions this syntax is the section before it:
"As written, the advantage of this functor specification technique is that it is also possible to pass an ordinary function pointer as argument. For example:
bool my_criterion () (T const& x, T const& y);
The code I'm trying to compile based on excerpt from the book:
template<typename F>
void mySort(F cmp)
{
std::cout << "mySort(F cmp)" << std::endl;
}
bool myCriterion()(int x, int y);
*error C2091: function returns function (referring to myCriterion)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我猜这是书上的错字。引用书中的内容:
作者显然试图声明“普通函数”。函数名称后面的一对括号不应该出现。
I'm going to guess that it's a typo in the book. Quoting from the book:
The authors are clearly trying to declare and "ordinary function". The pair of parentheses right after the function name shouldn't be there.
我的 C++ 有点生疏,但谷歌搜索发现了这一点:函数指针教程
My C++ is a bit rusty, but googling turned this up: The Function Pointer Tutorials
我想你缺少的是一个名为 Functor 的类:
这是一个小例子。
I suppose what you are missing is a class called Functor:
here is a small example.