c++ - Pass function as parameter to integrate object using lambda -


for educational purposes

i have function integrate takes in std::function parameter.

double calculus::integralsimple(std::function<double(double)> fn, double begin, double end) {     double integral = 0;      (long double = begin; < end; += _step)     {         integral += fn(i) * _step;  // _step defined in class      }     return integral; } 

currently calling function main.cpp using

calculus cl; std::cout << cl.integralsimple(calculus::identity,0,1); std::cout << cl.integralsimple([](double x) { return x*x; }, 0, 1); 

where identity static function defined in calculus.h , other uses lambda function.

i wondering whether make syntax easier user , closer mathematics way. prefer user have type:

std::cout << cl.integralsimple( x*x ,0,1); // take function of form  std::cout << cl.integralsimple( x*sin(x) - x*x ,0,1); 

is there way achieve in c++?

that boost.lambda designed for. syntax this:

#include <iostream> #include <vector> #include <algorithm> #include <cmath> #include <boost/lambda/lambda.hpp> #include <boost/lambda/bind.hpp>  const double pi  =3.141592653589793238463;  double func(double v) { return std::sin(v); } // avoid having                                               // cast std::sin  int main() {     using namespace boost::lambda;      std::vector<double> v = {0, pi / 4, pi / 2, pi};      std::for_each(v.begin(), v.end(),         std::cout << _1 * bind(func, _1) - _1 * _1 << '\n'     //                    ↑↑↑↑↑↑↑↑↑↑↑↑↑↑     //                    delay invocation of func     ); } 

whether that's better c++11 lambda syntax or not entirely you.

note c++14 , abuse of features, can write expression want too:

auto x = _1;  auto sin(decltype(_1) ) {     return bind(static_cast<double(*)(double)>(std::sin), _1); } 

with that, can do:

std::for_each(v.begin(), v.end(),     std::cout << x * sin(x) - x * x << '\n'); 

which print same thing original example did. just... more cryptically.


Popular posts from this blog

html/hta mutiple file in audio player -

debugging - Reference - What does this error mean in PHP? -