GSL 中的静态虚拟解决方法
Static Virtual workaround in GSL
你好,我正在尝试编写一个小程序来模拟动态系统,使用GNU科学库中的微分方程包。问题不是特定于GSL,但我只是为您提供所有详细信息
在当前的设计中,我希望有一个抽象的Experiment
类,其中所有复杂的函数都将由 gsl 库调用。显式系统的动力学将由两个函数定义,即 func 和 jacob,它们分别定义了特定的运动方程和雅可比函数。因此,我想在 Experiment
类中进行所有模拟,并且只用将由Experiment
继承的特定类覆盖两个虚函数。
我遇到的问题是,作为虚拟方法,这些方法无法编译
error: argument of type ‘int (Experiment::)(double, const double*, double*, void*)’ does not match ‘int (*)(double, const double*, double*, void*)’
如果我使这两个函数静态,程序将编译,但我正在失去我想要为特定问题实现的功能。
显然,它们不能既是静态的又是虚拟的,那么有谁知道这个问题的任何解决方法吗?有什么建议可以更好地处理它吗?
提前谢谢。
编辑:下面的代码编译,但它们不是虚拟的
class Experiment
{
public:
Experiment();
~Experiment();
void setupExperiment();
static int func(double t, const double y[], double f[], void *params);
static int jac (double t, const double y[], double *dfdy, double dfdt[], void *params);
};
void Experiment::setupExperiment(){
double mu = 10;
gsl_odeiv2_system sys = {func, jac, 2, &mu}; //Here is the problem with virtual functions
}
class aSpecificProblem: public Experiment{
// I want to implement just the func and jac function which should be virtual above
};
>我假设函数定义中的void*
是用户指定的回调参数。在这种情况下,请使用此参数传递指向对象的指针,并使回调成为静态函数。在这个静态函数中,将此指针转换回正确的类型(Experiment*
(,并调用函数的非静态版本。
class Experiment
{
public:
Experiment();
~Experiment();
void setupExperiment();
static int static_func(double t, const double y[], double f[], void *params);
static int static_jac (double t, const double y[], double *dfdy, double dfdt[], void *params);
virtual int func(double t, const double y[], double f[]);
virtual int jac (double t, const double y[], double *dfdy, double dfdt[]);
};
void Experiment::setupExperiment()
{
gsl_odeiv2_system sys = {static_func, static_jac, 2, this}; //Here is the problem with virtual functions
}
int Experiment::static_func(double t, const double y[], double f[], void *params)
{
return ((Experiment*)params)->func(t, y, f);
}
int Experiment::static_jac (double t, const double y[], double *dfdy, double dfdt[], void *params)
{
return ((Experiment*)params)->jac(t, y, dfdy, dfdt);
}
class aSpecificProblem: public Experiment
{
public:
virtual int func(double t, const double y[], double f[]);
virtual int jac (double t, const double y[], double *dfdy, double dfdt[]);
};
相关文章:
- 有没有办法在 c++ 中同时生成随机数?如果没有,是否有解决方法?
- 从 int 中剥离位时,编译器会警告一个转换,但不警告其他转换.有解决方法吗?
- 是否有解决方法可以在 c++ 中为 short 定义用户定义的文字?
- 不为 emplace() 定义构造函数的解决方法
- 删除复制构造函数的 Intel 13.1.2 中不良C++行为的解决方法
- 函数模板部分专业化-有什么解决方法吗
- 带boost的过载模糊性:可选,解决方法
- 继承构造函数和其他变量的解决方法
- C++ 解决方法:"从类型"B*"的表达式初始化类型"C*&"的引用无效"
- 对前向声明类型进行unique_ptr的解决方法
- 解决方法:'can not be used when making a shared object; recompile with -fPIC'使用Cmake。使用普通的 g++ 工作
- 解决方法:QPixmap:在GUI线程之外使用pixmap是不安全的
- CreateProcessWithTokenW 的 cmdline 参数的最大长度是否有解决方法?
- C++双精度作为模板参数的解决方法
- 在参数相关查找之前进行模板替换的任何方法(或解决方法?
- CUDA 内核"Only a single pack parameter is allowed"解决方法?
- dlsym() 解决方法返回类型
- VS2017是否有VLA(可变长度阵列)支持解决方法
- 解决方法:未定义对"class::function"的引用
- 来自 Boost 的 JSON 解析器的警告 C4512 的解决方法