oalfishcivil said:
I have a function double solver(double (*pf)(double), double tol)
However, it would be nice if solver could work for function
double func(double x,double para) since the codes are similar.
How could I do that? Thanks
It is hard to figure out what is it exactly that you need, but at the
first sight it looks like you are looking for a "closure" functionality,
i.e. you want to convert a 'double (*)(double, double)' function pointer
to a 'double (*)(double)' function pointer by pre-assigning a fixed
second parameter value. Unfortunately, there's no elegant portable way
to do it in C++ as long as you stick with function pointers.
A possible workaround is to provide a wrapper function for your 'double
func(double x, double para)' and specify the 'para' value through a
global variable
double g_para;
double func_wrapper(double x) {
return func(x, g_para);
}
and then use 'func_wrapper' in calls to 'solver', not forgetting to set
the 'g_para' to the proper value in advance. This is, of course, a
rather inelegant solution, since it relies on a global variable. It is
not reentrant, which severely limits is usefulness.
P.S. Of course, if you can get rid of the callback entirely, as
Vladyslav suggested, it would be the right way to go. But if you really
need the callback, then you are pretty much stuck with the above.