I have a vector of KeyCallbacks:
typedef boost::function<void (const KeyEvent&)> KeyCallback
which I use to store all listeners for when a keyboard button is pressed. I can add them and dispatch the events to all callbacks with for_each, but I do not know how to actually erase a specific KeyCallback signature from my vector.
For example I want something like this:
void InputManager::UnregisterCallback(KeyCallback callback) {
mKeyCallbacks.erase(std::find(mKeyCallbacks.begin(), mKeyCallbacks.end(), callback));
}
According to boost::function documentation (see here), there is no such thing as comparing function objects, which would explain my problems with the above. So am I stuck? Is there any nice way around this?
(I read about boost::signals for callback mechanisms, but it’s apparently quite slow, and I expect callbacks to be fired possibly several times a frame.)
Approach #1:
http://www.boost.org/doc/libs/1_51_0/doc/html/function/tutorial.html#id1546064
So, one of solutions, is to define special type for UnregisterCallback’s parameter (which also supports type erasure). That is based on fact, that you can compare boost::function with functor/function – as the result you still will have vector of boost::function, new type is required only for places where you need to perform comparison, e.g. UnregisterCallback:
LIVE DEMO
Output is:
Pros:
Cons:
Approach #2:
Another approach is to implement custom boost::function-like solution, which accepts comparable-only callbacks.
LIVE DEMO
Output is:
Pros:
Cons:
Approach #3:
Here we are creating new class which is inherited from std/boost ::function
LIVE DEMO
Output is:
Pros:
Cons:
EDIT:
boost::function can be compared against functions or functors, but not against another boost::function:
In our #1 approach, we do comparison similar to “bf1 == f1;”. KeyCallbackChecker captures functor/function and performs such kind of comparison inside ConcreteCallback::equals.