vendredi 26 décembre 2014

Application design for callbacks with derived classes

I am trying to design application with callbacks which arguments vary. There is one central class Application which defines all callbacks. Then there is class Connection, which should store those callbacks (already bound).


Application looks like this:



class Application {

public:
void firstCallback(DerivedFrist *obj) { }
void secondCallback(DerivedSecond *obj) { }
};


Then there is this Connection class which should store registered callbacks and call them when some internal event fires.



class Connection {

private:
map<int, ??> callbacks; // what to do if I want it to be typesafe?
public:
void registerCallback(int condition, Callback callback) {
callbacks[condition] = callback;
}

void fireCallback(int condition, Base *obj) {
callbacks[condition](obj); // call the callback from the map (with base object?)
}
};


This is my approach to the application, which leads to errors when trying to implement with std::function due to type differention. I may reinterpret cast the arguments but that may lead to undefined behaviour.


Is there any good approach to do this? Any patterns are welcome. Thank you!


Aucun commentaire:

Enregistrer un commentaire