加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 通用成员函数指针作为另一个类内的模板参数

发布时间:2020-12-16 07:03:50 所属栏目:百科 来源:网络整理
导读:我的问题类似于 this.而’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
我的问题类似于 this.而’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;
   }
};

我有另一个类应该能够存储任何类型和数量的args的通用成员函数.该类看起来像这样:

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;
};

现在我想从主要向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;
}

编译代码时出现以下错误.

no matching function for call to 'MFHolder::addMF(A1&,void (A1::*)(int),int&)'

候选人是:

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

Thx提前!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读