我想实现一个回调管理器,它可以注册和执行不同类的回调,每个类都来自不同的DLL。回调函数设计C++
这些类中的每一个派生自一个公共基类。我知道单个类可以如何使用像下面这样的模板类来注册和调用它自己的函数,但是如何将它应用于共享相同回调管理器的多个类?
任何帮助将不胜感激。
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;
}
LF不使用模板化的回调经理,我怎么能实现像SetFunPointer(EVENT_NAME,(基类)A :: testCallback)?
您在这里认识到,cCallBackManager成员或类A与B类的cCallBackManager不一样,也不像main那样,对吧? – 2012-07-07 05:30:47
是的。我的问题是他们如何共享一个回调管理器? – 2012-07-07 06:05:42
回调管理器应该是一个独立的对象。这里它将是main()中的局部变量。更重要的是,我认为你应该重新思考你的“回调管理器”究竟是什么。在实现其功能之前考虑它的接口。注意你有一个“Getxxxx”函数,它不返回任何东西。什么是你的功能的来电者“获取?” – 2012-07-07 06:24:28