【发布时间】:2010-07-15 20:20:55
【问题描述】:
我在 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);
我需要自己提供一个 integrand 类型的 void 函数,adapter_integrate 将计算 n 维积分。如果func 是独立函数,则calcTripleIntegral(如下)中的代码作为独立函数工作)。
我想传递一个(非静态!)类成员函数作为被积函数,因为它很容易被重载等等......
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 进行编译,都导致相同的错误。要么没有做任何工作,要么我做错了什么/EDIT
非常感谢非常!如果我不够清楚,我很乐意详细说明。
PS:我可以通过使用指向 myIntegrator.cpp 中某处定义的函数的函数指针来解决这个问题吗?
最终更新:好的,我误以为 TR1 提供了一个/两行解决方案。真可惜。我正在将我的类“转换”为命名空间并复制粘贴函数声明。我只需要一个基类和一个重新实现接口的子类。 C 函数指针 + C++ class= 对我来说是个坏消息。 无论如何感谢所有答案,您向我展示了 C++ 的一些黑暗角落;)
【问题讨论】:
-
fdata和input参数是关于什么的?为什么被积函数类型中的void*参数没有名字? -
Caspin,你不需要在类型声明中命名函数的参数。如果您不需要在函数中使用它们,您甚至不需要在函数的实际定义中命名它们。如果他们的函数需要匹配某个签名以与其他代码一起使用,人们通常会写这个,但有些参数永远不会在他们的实现中使用。
-
@A.Le:Caspin 知道这一点。问题是我们不知道
void* fdata是否被传递——如果integrand的void*参数被恰当地命名,我们就不必猜测/询问。 -
啊!傻我!我把一个主要问题误认为是真正的无知。对不起卡斯平!
-
我知道当我问它时,有人会向我解释为什么不需要它们。也许我应该在我的问题前加上“我知道……”。