模板参数推导/替换使用lambda表达式

时间:2016-12-08 19:20:21

标签: c++ function debugging templates lambda

所以我想创建一个模板函数,它将一个函数作为T类型的参数。

#include<functional>
template<typename T>
T bisection(T xL, T xR, T epsilon, std::function<T(T)> fx)

现在,在主程序中,以下调用给出了错误。

 bisection(0.0, 2.0, 0.001, [](double x){return x*x-2;})

错误讯息:

bisection.cpp: In function ‘int main()’:
bisection.cpp:24:65: error: no matching function for call to 
‘bisection(double, double, double, main()::<lambda(double)>)’
cout << bisection(0.0, 2.0, 0.001, [](double x){return x*x-2;}) << endl;
                                                             ^
bisection.cpp:6:3: note: candidate: template<class T> T bisection(T, T,
T, std::function<T(T)>)
T bisection(T xL, T xR, T epsilon, std::function<T(T)> fx)
^
bisection.cpp:6:3: note:   template argument deduction/substitution  failed:
bisection.cpp:24:65: note:   ‘main()::<lambda(double)>’ is not derived from ‘std::function<T(T)>’
cout << bisection(0.0, 2.0, 0.001, [](double x){return x*x-2;}) << endl;

请建议如何纠正此错误。 如果我将二分的函数签名更改为:

,程序可以正常工作
T bisection(T xL, T xR, T epsilon, std::function<double(double)> fx)

1 个答案:

答案 0 :(得分:2)

lambda不是std::function,更简单的是

template<typename T, template F>
T bisection(T xL, T xR, T epsilon, F&& fx);