Let's say I have an integration function double integral(double (*f)(double), double a, double b) which computes the integral of f(x) in [a,b]. However, I am in a situation where f is not known in compile time, and may change during runtime. Therefore in my current design, I have a class that tracks and mutates several f1, f2, f3 etc.. However, since f1, f2, f3 etc are now a member of a class, I can't just take its function pointer &my_class::f1 and feed it to integral(f1,a,b). The ideal way of doing this would be to just spit out a lambda function during runtime.
Some pseudo code to be more precise about what I want:
double integral(double (*f)(double), double a, double b);
class secret {
public:
// all three of these rely on internal state that this class manages
// absolutely none of these methods can be static!
double f1(double x);
double f2(double x);
double f3(double x);
void do_stuff(); // mutates internal state, changing the behavior of f1,f2,f3
void do_something_else(); // mutates internal state, changing the behavior of f1,f2,f3
double execute(); // internally, this function calls integrate(f1,a,b), integrate(f2,a,b) and integrate(f3,a,b)
}
// needs to handle functions that are not part of a class
double quadratic(double x) {
return x*x;
}
int main() {
secret s1, s2;
s1.do_stuff() // change the state of s1, changing f1,f2,f3
s2.do_something_else() // change the state of s2.
// We can have multiple instances of the secret class, all with different internal state,
// but need the ability to call "integral" with a lot of freedom
// I want a good design that will let me do this kind of thing
cout<<integrate(&s1.f1, 0, 1)<<endl;
cout<<integrate(&quadratic, 0, 1)<<endl;
cout<<integrate(&s2.f1, 0, 1)<<endl;
cout<<s1.execute()<<endl;
cout<<s2.execute()<<endl;
}
I am limited to an old machine that only supports C++11. My question is in two parts, what is the best design to do this in C++11, and what is the best design in g++ 9.2?