visual c++ - callback function design C++ -


i'm trying implement callback manager can register , execute callbacks different classes, each classes different dll.

each of these classes derives common base class. know how single class can make use of template class below register , call own function, how can applied use on multiple classes sharing same callback manager?

any appreciated.

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 call without knowing type? { (funcmap::iterator = 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 generalize can called callback manager 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; b b; //create callback manager execute callback? callbackmgr.execute() //execute callback return 0; } 

lf not using templatized callback manager, how can achieve setfunpointer(event_name, (base class)a::testcallback)?

thanks guys. i've managed come "pointers". :)

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

file: 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 doing something." << endl; } }; 

file: main.cpp

int main() { derived a; std::vector<callbackinterface> callback; callback.push_back(callbackinterface(&a, (basefn)(&derived::adosomething))); for(int = 0; < callback.size(); i++) callback[i].execute(); return 0; } 

Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -