从另一个类调用指向成员函数的指针

时间:2014-02-27 22:28:43

标签: c++ pointers

我有一个正交类,我希望能够将任何被积函数传递给它,无论定义被积函数的函数是自由函数还是另一个类的成员函数。对于后一种情况,我所取得的最佳进展如下。

ChiSquared包含指向GaussQuadrature类的指针,并将成员函数传递给名为GaussQuadrature的{​​{1}},如下所示:

Quad

double ChiSquared::LowerIncompleteGammaIntegrand(double x) { return pow(x, (5/2.0)-1)*exp(-x); } double ChiSquared::LowerIncompleteGamma(double x) { Quad->Quadrature(&ChiSquared::LowerIncompleteGammaIntegrand, other args...); return Quad->getQuad(); } 模板类中,接受此调用的GaussQuadrature函数是

Quadrature

首先,这会产生错误

template<typename T>
void GaussQuadrature<T>::
Quadrature(double (ChiSquared::*Integrand)(double), other args...)
{
   T val = Integrand(argument);
   ...
   // other math stuff
}

这使我觉得我需要error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘Integrand (...)’, e.g. ‘(... ->* Integrand) (...)’ 类中ChiSquared的实例,而不是相反,我想避免这种情况,因为:

其次,我想将GaussQuadrature类与任何其他类分离,如前所述。理想情况下,任何函数都可以作为“被积函数”传递,因此我不想为“integrand”可能来自的每种可能类型的类声明一个单独的GaussQuadature函数。我可以在这里使用某种功能模板吗?

2 个答案:

答案 0 :(得分:2)

你可以尝试

double ChiSquared::LowerIncompleteGamma(double x) {
    std::function<double(double)> f =
        std::bind( &ChiSquared::LowerIncompleteGammaIntegrand, *this, _1 );
    Quad->Quadrature(f, other args...);
    return Quad->getQuad();
}

修改GaussQuadrature以获取function<...>参数,或将其作为模板:

template<typename T>
template<typename F>
void GaussQuadrature<T>::
Quadrature(const F& Integrand, other args...)
{
   T val = Integrand(argument);
   ...
   // other math stuff
}

在这里,std::bindChiSquared对象*this与其方法LowerIncompleteGammaIntegrand()绑定在一起,给出一个带有double参数并返回{{1}的函数}};然后,std::function仅使用其签名double表示此内容,隐藏基础类型double(double)

顺便说一下,有些东西显然是缺失的,例如我无法在ChiSquared中看到参数x的位置,或ChiSquared::LowerIncompleteGamma()中来自argument的位置。

答案 1 :(得分:0)

可能你应该省略函数签名中的其他类吗?

template<typename T> void GaussQuadrature<T>::
Quadrature(double (*Integrand)(double), other args...)
{
   T val = Integrand(argument);
   ...
   // other math stuff
}