泛型成员函数指针作为另一个类中的模板参数

Generic member function pointer as template parameter inside another class

本文关键字:参数 另一个 函数 成员 指针 泛型      更新时间:2023-10-16

我的问题与此类似。Karrek SB的回答在某种程度上帮助了我。我有这些类:

Base.h:

class Base{
public:
   Base(){}
   virtual ~Base(){}
   virtual void init() = 0;
};

A1.h:

#include <iostream>
#include "Base.h"
using namespace std;
class A1 : public Base{
public:
   A1(){}
   virtual ~A1(){};
   virtual void init(){
      cout << "A1::init() called" << endl;
   }
   void f1(){
      cout << "Im in A1::f1" << endl;
   }
   void f2(int val){
      cout << "Im in A1::f2 with val: " << val << endl;
   }
};

我有另一个类,它应该能够存储具有任何类型和数量的参数的任何泛型成员函数。该类看起来像这样:

MFholder.h:

#include <functional>
#include <deque>
using namespace std;
class MFHolder{
    public:
       MFHolder(){};
       ~MFHolder(){};
       template<typename T, typename R, typename ... Args>
       R addMF(T & obj, R (T::*pf)(Args ...), Args&& ... args){
           mfp.push_back(function<void()>(bind(pf, &obj, forward<Args>(args) ...)));
       }
       void runTasks(){
           while(!mfp.empty()){
               auto task = mfp.front();
               mfp.pop_front();
               task();
           }
       }
    private:
       deque< function<void()> > mfp;
};

现在我想从main中添加一些成员函数到MFHolder,像这样:main.cpp:

#include "A1.h"
#include "MFHolder.h"
int main(){
   MFHolder mfh;
   A1 a1Obj;
   //A2 a2Obj; //this should also work
   int val = 42;
   //mfh.addMF(a1Obj, &A1::f1); //this should also work
   mfh.addMF(a1Obj, &A1::f2, val);
   //add some more function calls here...

   //run all the tasks
   mfh.runTasks();
   return 0;
}

在编译我的代码时,我得到以下错误:

呼叫'MFHolder::addMF(A1&, void (A1::*)(int), int&)'没有匹配函数

候选人是:

template<class T, class R, class ... Args> R MFHolder::addMF(T&, R (T::*)(Args ...), Args&& ...)

提前感谢!:)

Args&在addMF的定义中,或者在调用它时将val更改为move(val)

相关文章: