不能用函数参数调用函数模板
Cannot call function template with function argument
我一辈子也弄不清楚这个函数模板中我需要调用的参数类型的复杂组合是怎么回事。我试图调用一个函数模板,有这个签名:
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;
}
相关文章:
- C++有什么方法可以在既不调用函数模板也不提供其模板参数的情况下引用函数模板?
- C++如果两个模板函数都与参数列表匹配,将调用哪个模板
- 如何在类模板的成员函数中正确调用函数对象?正在生成 Visual Studio 编译器错误 C2440
- 为什么没有调用此模板类的复制构造函数?
- 调用类模板中隐式删除的复制构造函数
- 从模板化函数调用非模板化函数
- 从类似构造函数的调用返回模板化智能指针
- 从模板化类虚拟函数中调用的模板函数不正确
- 需要"模板<>"语法 --> 通过函数调用类模板
- 模板 使用数据数组调用函数时扩展参数包
- C++,当函子不是一个选项时,我如何编写带有自定义函数调用的模板化 RAII 包装器?
- 调用类模板的成员函数模板
- 如何从前面定义的另一个函数调用函数模板
- 未为派生类型调用函数模板专用化
- Lambda函数无法调用函数模板参数的静态函数
- 不能用函数参数调用函数模板
- 使用函数指针调用函数模板
- 调用函数模板时出错"No matching function"
- 为派生的可变参数类模板调用函数模板重载
- 使用C调用约定调用函数模板专门化