I have consult (disclaimer):
- Class member function pointer
- Calling C++ class methods via a function pointer
- C++: Function pointer to another class function
To illustrate my problem I will use this code (UPDATED)
#include <iostream>
#include <cmath>
#include <functional>
class Solver{
public:
int Optimize(const std::function<double(double,double>& function_to_optimize),double start_val, double &opt_val){
opt_val = function_to_optimize(start_val);
return 0;
}
};
class FunctionExample{
public:
double Value(double x,double y)
{
return x+y;
}
};
int main(){
FunctionExample F =FunctionExample();
Solver MySolver=Solver();
double global_opt=0.0;
MySolver.Optimize(std::bind(&FunctionExample::Value, &F, std::placeholders::_2),1,global_opt);
return 0;
}
Is there a way to call the method "Value"? I have no problems to call a function (without a class)
typedef double (*FunctionValuePtr)(double x);
But this does not help me with the example above. I need the explicit method name. Most examples use a static method. I can not use a static method.
You can use the
<functional>
header of the STL:Also like Joachim Pileborg commented you are declaring functions in main, so you need to remove the
()
.Edit:
To give bind a fixed argument you can do the following:
This will call
F.Value(opt_val, 1)
. You can also swap the placeholder with the fixed argument.