Return a function with parameters evaluated

  • A+

I am fairly new to C++ and I would like to do the following but can't figure out how.

I want to define a function based on a template with some parameters. Lets say we have f(x)=a*x+b, but the parameters a and b will be passed as parameters.

I would like to define a function create_function(double a, double b) that returns a*x+b with a and b evaluated to whatever the parameters are passed so that I can use another function func( double x ) to evaluate it.

The goal is to just create the function once with given parameters so that it can then be repeatedly called by another routine as just f(x). The real function is much more complex than this but I'll be able to adapt it.

I've been looking at this post and it would be something similar to this but I don't know how to adapt it to returning a function that still depends on x.


You can do this with lambdas:

auto create_function(double a, double b) {   return [a, b](double x) { return a * x + b; }; }  void test() {   auto func = create_function(2.0, 3.0);   double y = func(4.0); // y is now 11 } 

Demo (shows that the compiler already knows func(4.0) will always return 11)


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: