I need to create a function which will return a pointer to another function as a result so that I could write something like f(n)(v)
in main()
.
Think more general! Let me reformulate this just a bit: You need to create a function that returns something so that you can write f(n)(v)
in main()
.
This something must not necessarily be a function (or function pointer). If we stick to this syntax f(n)(v)
, then it definitely has to be a callable. Note that "callable" can be many things. All that we need for some object F
to be callable is that F(v)
is valid for certain types of v
.
A rather traditional type of callables are functors. A functor is an object of a class that has an operator()
. I don't wont to give away the full free lunch, so for the sake of the example I will restrict myself to linear functions (extension to polynomials should be straight-forward).
We start by defining the functor class:
struct linear_fun {
double a;
double b;
double operator()(double x) { return a + b*x; }
};
Once we have this, passing around a function object is as simple as it can get:
// returns a linear_fun that crosses the origin and the given point
linear_fun fun_crossing_point(double x,double y) {
return { 0.0 , y / x };
}
Lastly we want to test it
int main() {
std::cout << fun_crossing_point( 1.1 , 5.0 )(1.1);
}
Prints:
5
Note that there are also lambdas which are basically syntactic sugar for functor classes. They come in handy when you want to define the functor only in a narrow scope. The downside is that every lambda is of different type, so when you want one specific type then it is worth to consider writing the functor class yourself.
Also C++ has std::function
, which is the catch-it-all solution for callables. It comes with great flexibility, because a single std::function
object can be assigned almost any kind of callable. However, this flexibility comes at some cost and usually one does not need it. I presume you just need to define one type that defines your polynomial and you do not need to mix eg free functions, member functions and others.