问题
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.
回答1:
You can use the <functional>
header of the STL:
double Gradient(const std::function<double(double)>& func, double y)
{
const double h = 1e-5;
return (func(y+h) - func(y)) / h;
}
std::cout << D.Gradient(std::bind(&Root::Value, &R, std::placeholders::_1), 8) << std::endl;
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:
int Optimize(const std::function<double(double)>& function_to_optimize, double &opt_val){
opt_val = function_to_optimize(opt_val);
return 0;
}
MySolver.Optimize(std::bind(&FunctionExample::Value, &F, std::placeholders::_1, 1), global_opt);
This will call F.Value(opt_val, 1)
. You can also swap the placeholder with the fixed argument.
来源:https://stackoverflow.com/questions/21582223/one-class-should-invoke-method-of-another-class-using-a-function-pointer