0
所以我想創建一個模板函數,它接受一個函數作爲T類型的參數現在模板參數推導/替換使用lambda表達式失敗,高階函數
#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)