泛型成员函数指针作为另一个类中的模板参数
Generic member function pointer as template parameter inside another class
我的问题与此类似。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)
相关文章:
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 修改函数中的指针(将另一个指针作为参数传递)
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- 如果需要转换,我可以在读取参数的同时将其移动到另一个参数吗?
- 如何在另一个函数中使用返回值作为参数?
- 如果模板参数是另一个模板的实例化,则键入特征测试
- 如何使用另一个类中的公共成员函数作为参数调用线程
- 如何将 lambda 函数作为参数发送到另一个函数
- 将可变参数从一个函数传递到另一个函数
- 如何在C++中提供模板化函数作为另一个函数的参数,默认值?
- 将一个宏传递到另一个宏而不是直接传递内容时会出现不需要的额外"空"参数
- 无法将指向类的成员函数的函数指针作为参数传递给同一类的另一个成员函数
- 如何设置默认参数以防用户不输入另一个参数
- C++ 如何根据作为输入传递的参数调用一个构造函数或另一个构造函数?
- 编译器在C++中调用另一个函数时,在参数中查找已删除的构造函数
- 将另一个类的成员函数传递到 std::function 参数中
- 如何参数化用作另一个 lambda 参数的 lambda
- 将参数从一个函数传递到另一个函数(没有模板) - C++
- 重构模板类,该类将其嵌套类用作另一个类的模板参数