我想實現一個回調管理器,它可以註冊和執行不同類的回調,每個類都來自不同的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