不能用函数参数调用函数模板

Cannot call function template with function argument

本文关键字:调用 函数模板 参数 函数 不能      更新时间:2023-10-16

我一辈子也弄不清楚这个函数模板中我需要调用的参数类型的复杂组合是怎么回事。我试图调用一个函数模板,有这个签名:

template <class T> list<T> map(T (*f)(const T &i), const list<T> &il);

我的代码是这样的:

int successor(int n) {
    return n+1;
}
int main ()
{
    list<int> seq = ez_list(0,1,2,3,4);  // I know that this part is right
    map(successor, seq); // this function call is not recognized
    return 0;
}

Eclipse显示"无效参数"候选者为:list<#0> map(#0 (*)(const #0 &), const list<#0>,但我看不出这与我所拥有的有何不同。请向我解释我的参数有什么问题,即它们是如何无法匹配函数模板签名的,以及它们应该是什么样子来适应它。

编辑:感谢大家对如何使这个更干净的建议,不幸的是,地图的定义是从别人的代码,我只需要工作。我会把你的建议记在心里,以便将来使用。

int successor(int n)int successor(const int& n)不一样

@StoryTeller说的是对的…但事情远不止这些。

这将解决当前的问题,即函数签名不匹配,因为常量参数,你必须传递地址函数....

int successor(const int& n) {
    return n+1;
}
int main ()
{
    list<int> seq = ez_list(0,1,2,3,4);  
    map(&successor, seq); // pass the address of the function
    return 0;
}

现在,对于第二个问题。为了将来阅读你代码的每个人,请不要这样做。使用函子代替:

template<typename T>
class MyFunctor 
{
   public:
   T operator()(const T& arg) 
   {
      //Do your function work in here...
   }
}

(见http://www.cprogramming.com/tutorial/functors-function-objects-in-c++.html关于函数对象的深入描述)

当然,这可以非常简洁,所以如果你想包装一个函数指针,c++有相应的功能。现在你可以包装你的函数对象,而不用担心指针语法:

#include <functional>
template <class T> list<T> map(std::function<T(const T&), const list<T> &il);
int successor(int n) {
    return n+1;
}
int main ()
{
    list<int> seq = ez_list(0,1,2,3,4);  // I know that this part is right
    std::function<T (const T&)> successor = std::bind(&successor, std::placeholders::_1);
    map(successor, seq); // Look, ma, no function pointer!
    return 0;
}