gpt4 book ai didi

c++ - 函数调用语法?

转载 作者:行者123 更新时间:2023-11-28 03:42:34 26 4
gpt4 key购买 nike

阅读“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);

我用适当的值替换了所有的 .. 并将 T 替换为 my_criterion() 中的 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:函数返回函数(指myCriterion)

最佳答案

我猜这是书中的错别字。引自书中:

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); 
// call function with function object
my_sort (… , my_criterion);

作者显然是在试图声明和“普通函数”。函数名后面的一对括号不应该出现。

关于c++ - 函数调用语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8648556/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com