一个类应该使用函数指针来调用另一类的方法 [英] one class should invoke method of another class using a function pointer
问题描述
我已咨询(免责声明):
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;
}
有没有一种方法可以调用方法"Value"?我没有问题可以调用一个函数(没有类)
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.
推荐答案
您可以使用STL的<functional>
标头:
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;
就像乔亚希姆·皮尔博格(Joachim Pileborg)所说的那样,您在main中声明了函数,因此您需要删除()
.
Also like Joachim Pileborg commented you are declaring functions in main, so you need to remove the ()
.
要为bind提供一个固定的参数,您可以执行以下操作:
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);
这将称为F.Value(opt_val, 1)
.您还可以将占位符与固定参数互换.
This will call F.Value(opt_val, 1)
. You can also swap the placeholder with the fixed argument.
这篇关于一个类应该使用函数指针来调用另一类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!