c++ - 如何将类成员函数传递给第 3 方库中的方法?

标签 c++ class templates pointer-to-member

以下是我想在第 3 方库中使用的类的构造函数(因此不能选择更改此函数)。

template <class Space>
moveset<Space>::moveset(particle<Space> (*pfInit)(rng*),
          void (*pfNewMoves)(long, particle<Space> &,rng*),
          int (*pfNewMCMC)(long,particle<Space> &,rng*))

但是,我不是简单地定义 3 个全局函数,而是需要每个函数都知道各种额外信息,显然我不能传递这些信息,因为没有输入参数。为了使问题进一步复杂化,我将要创建此 moveset 对象的多个不同实例,每个实例都希望使用相同的函数,但基于不同的基础数据。

我的想法是按照这些思路创建一个控股类,

Class DataPlusFunctions {

 public:

   DataPlusFunctions(Data* dataPtr) { dataPtr_ = dataPtr ;}

   smc::particle<cv_state> fInitialise(smc::rng *pRng)
    {

      // the actual function will be a lot more complicated than this and
      // likely to require calling other methods / classes.
      // The Data stored in a different class will be changing...which is
      // important in relation to the pfNewMoves function.

      double value = dataPtr_->value() ;
      return smc::particle<cv_state>(value,likelihood(0,value));          

    }

    ... same for other required functions
 private:

  Data* dataPtr_ ;
}

*

Class MainClass {

...
void IK_PFController::initialise() 
{

   std::vector<DataPlusFunctions> dpfV ;

   for (int i = 0 ; i < NSAMPLERS ; i++)
        dpfV.push_back(DataPlusFunctions(&data[i])) ;


  pSamplers_ = (smc::sampler<cv_state>**)(new void* [NSAMPLERS]) ;

  for (int i = 0 ; i < NSAMPLERS ; i++) {

    // Normal way of calling function, having defined global functions e.g.
    //smc::moveset<cv_state> Moveset(fInitialise, fMove, NULL);

    // How to achieve this given my problem ??????????????
    //smc::moveset<cv_state> Moveset(&dpfV[i]::fInitialise, &dpfV[i]::fMove, NULL);

     pSamplers_[i].SetMoveSet(Moveset);

  }

} 

}

是否允许?如果没有,是否有可能实现我正在尝试的,因为我将能够改变移动组类?

最佳答案

为了调用成员函数(通过指针),您需要一个适当类型的对象。由于第 3 方函数需要原始函数指针,因此您不能传递成员函数。

你能做的最好的事情(AFAIK)是定义三个函数

particle<Space> Init(rng*);
void NewMoves(long, particle<Space> &,rng*);
int NewMCMC(long,particle<Space> &,rng*);

并设置这些函数访问的全局变量。例如:

DataPlusFunctions* g = NULL;

particle<Space> Init(rng* r)
{
  // g==NULL handling omitted
  return g->fInitialise(r);
}
// similarly for the others

并在调用第 3 方函数之前设置 g 的值。

优点是您有一个可用于存储状态信息的对象,您还可以将指向的对象替换为另一个对象(甚至可以使用接口(interface)),从而提供动态行为。

问题是,如果您想在并行设置中使用它,因为全局可能会同时被两个线程更改——在这种情况下,您可以使用互斥锁或锁来保护它。

关于c++ - 如何将类成员函数传递给第 3 方库中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9997299/

相关文章:

c++ - 如何访问在另一个类中声明的类?

Ruby:从模块中重新打开类

c++ - 传递给共享库的模板函数 (c++)

c++ - C++中调用类模板的函数模板

c++ - osgDB/FileUtils在我的代码中导致编译器错误

c++ - 为什么我们需要定义类的静态变量,而不是类的其他成员?

c++ - 使用 Copliens 1994 计数指针示例代码获取编译错误

c++ - 类里面没有失忆

c# - 我是否使用了错误的设置/获取功能?

c++ - GCC模板问题