I use a function from an optimization toolbox that numerically calculates derivatives of functions. It accepts a pointer to a function with one argument, but what if I need to pass a pointer to a function with multiple arguments to it and expect the additional, less important parameters to just be passed through?
//Function from toolbox
double num_differentation(double (func(const double)), double x)
{
//makes various calls to func, but with only one parameter
func(x);
}
Now assume I have a function I'd like to pass to the above but which has additional arguments not directly related to the optimization problem, but that are nevertheless required to arrive at a meaningful result for the function.
double my_func_to_be_input(double a, double b, double c) {
return a+b*c;
}
Is there a way to rewrite num_differentiation so that at the time of calling func it passes through all three parameters? I tried the following but it did not work:
double num_differentation(double (func(const double arg1, const double arg2, const double arg3)), double x)
{
//makes various calls to func, but with only one parameter
func(x, arg2, arg3);
}
And if we wanted to be even more fancy, would it be possible for num_differentiation to accept a function with varying numbers of parameters with the irrelevant ones just being passed through?
In any case, I would not like to have to resort to global variables to route these additional parameters.
I'm using Visual Studio 2013 and would welcome any helpful suggestions, especially with concrete code examples.
UPDATE: This is how I solved it.
//Rewritten function from toolbox
double rewritten_num_differentation(std::function<double(double)> func, double x)
{
func(x);
}
In my main code:
using namespace std::placeholders;
auto my_func_to_be_input_with_forwarded_arguments= std::bind(my_func_to_be_input, _1, second_argument_to_be_forwarded, third_argument_to_be_forwarded);
return rewritten_num_differentiation(my_func_to_be_input_with_forwarded_arguments, x_arg);
This is akin to CrazyEdie's suggested first solution. Perhaps there are still more elegant ways that do not involve rewriting the toolbox function, but it seems to be awfully complicated to convert the std::function type to a C-style function pointer (like they try here http://www.cplusplus.com/forum/general/63552/).