我正在尝试实现一个回调管理器,它可以注册和执行来自不同类的回调,每个类来自不同的DLL。
这些类中的每一个都派生自一个公共基类。我知道单个类如何使用类似下面的模板类来注册和调用它自己的函数,但是如何将它应用于共享同一个回调管理器的多个类?
非常感谢任何帮助。
file: callbacktemplate.h
------------------------
#include <functional>
#include <string>
template <class cInstance>
class cCallBackManager
{
private:
typedef void (cInstance::*tFunction)();
typedef std::map<std::string, tFunction> funcMap;
funcMap i_funcMap;
public:
void SetFunPointer(std::string funcName, tFunction function)
{
i_funcMap.insert(std::pair<std::string, tFunction>(funcName, function));
}
void GetFunPointer(cInstance& obj) //how to call this without knowing the type?
{
for (funcMap::iterator it = i_funcMap.begin();it!=i_funcMap.end(); ++it)
{
(obj.*(it->second))();
}
}
};
file:example.h
---------------
#include "callbacktemplate.h"
class A: public base
{
private:
cCallBackManager<A> callback;
public:
A()
{
callback.SetFunPointer<A>("eventA", &A::testcallback);
callback.GetFunPointer(&this); //how to generalize this so this can be called from the callback manager with the class object?
};
~A(){};
void testCallback();
};
class B: public base
{
private:
cCallBackManager<B> callback;
public:
B()
{
callback.SetFunPointer<B>("eventB", &B::testcallback);
};
~B(){};
void testCallback();
};
file: main.cpp
------------------
#include "derived.h"
int main()
{
A a;
B b;
//create a callback manager to execute the callback?
callbackmgr.execute() //execute all the callback
return 0;
}
如果没有使用模板化的回调管理器,我怎样才能实现像SetFunPointer(EVENT_NAME,(基类)A :: testCallback)?
答案 0 :(得分:1)
谢谢你们。我已经设法用你的“指针”来提出一些东西。 :)
文件:cCallBackInterface.h
template<class cClass>
class cCallBackInterface
{
public:
cCallBackInterface(){};
~cCallBackInterface(){};
typedef void (cClass::*Function)();
cCallBackInterface(cClass* obj, Function _Function)
{
cInstance = obj;
m_Function = _Function;
}
void execute()
{
(cInstance->*m_Function)();
}
private:
cClass* cInstance;
Function m_Function;
};
文件:base.h
class BaseModel;
typedef cCallBackInterface<BaseModel> CallBackInterface;
typedef void(BaseModel::*basefn)();
class BaseModel
{
public:
BaseModel(){};
~BaseModel(){};
}
};
class derived : public BaseModel
{
public:
derived(){};
~derived(){};
void dosomething()
{
cout << "derived class is doing something." << endl;
}
};
文件:main.cpp
int main()
{
derived a;
std::vector<CallBackInterface> callback;
callback.push_back(CallBackInterface(&a, (basefn)(&derived::Adosomething)));
for(int i = 0; i < callback.size(); i++)
callback[i].execute();
return 0;
}
答案 1 :(得分:0)
您可以查看有关using member-function pointers的问题。
它归结为你需要实例以及mem-func指针,你不能在任何地方使用通用的。