我在 C++ 类中使用非常复杂的 C 函数时遇到问题(重写 C 函数不是一种选择)。C函数:
typedef void (*integrand) (unsigned ndim, const double* x, void* fdata,
unsigned fdim, double* fval);
// This one:
int adapt_integrate(unsigned fdim, integrand f, void* fdata,
unsigned dim, const double* xmin, const double* xmax,
unsigned maxEval, double reqAbsError, double reqRelError,
double* val, double* err);
我需要自己提供一个 void 类型的函数integrand
,而 adapt_integrate 将计算 n 维积分。calcTripleIntegral
如果是独立函数,则(下面)中的代码作为独立函数func
工作)。我想传递一个(非静态!)类成员函数作为被积函数,因为这很容易重载等......
class myIntegrator
{
public:
double calcTripleIntegral( double x, double Q2, std::tr1::function<integrand> &func ) const
{
//...declare val, err, xMin, xMax and input(x,Q2) ...//
adapt_integrate( 1, func, input,
3, xMin, xMax,
0, 0, 1e-4,
&val, &err);
return val;
}
double integrandF2( unsigned ndim, const double *x, void *, // no matter what's inside
unsigned fdim, double *fval) const; // this qualifies as an integrand if it were not a class member
double getValue( double x, double Q2 ) const
{
std::tr1::function<integrand> func(std::tr1::bind(&myIntegrator::integrandF2, *this);
return calcTripleIntegral(x,Q2,func);
}
}
在 GCC 4.4.5(预发行版)上,这给了我:
错误:变量 'std::tr1::function func' 具有初始化程序但类型不完整
编辑:我的代码有什么错误?我现在尝试使用 GCC 4.4、4.5 和 4.6 进行编译,都导致相同的错误。要么没有做任何工作,要么我做错了什么/编辑
非常感谢!如果我不够清楚,我会很乐意详细说明。
PS:我可以通过使用指向 myIntegrator.cpp 中某处定义的函数的函数指针来解决这个问题吗?
最终更新:好的,我错误地认为 TR1 为此提供了一个/两行解决方案。真可惜。我正在将我的类“转换”为命名空间并复制粘贴函数声明。我只需要一个基类和一个重新实现接口的子类。C 函数指针 + C++ 类 = 对我来说是个坏消息。无论如何感谢所有答案,你已经向我展示了 C++ 的一些黑暗角落;)