0

So I wanted to create a template function which takes a function as an argument of type T.

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

Now, in the main program, the following call is giving error.

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

Error message:

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;

Kindly suggest how to rectify this error. The program works fine if I change the function signature of bisection to:

T bisection(T xL, T xR, T epsilon, std::function<double(double)> fx)
Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

2

lambda are not a std::function, the simpler would be

template<typename T, template F>
T bisection(T xL, T xR, T epsilon, F&& fx);
Jarod42
  • 203,559
  • 14
  • 181
  • 302