In addition to Yakk's answer, another usual way to implement this is to keep an iterator to the item in the container (this iterator acts at the "token" Yakk talks about).
Since you will possibly be deleting and adding other items before you get to delete a particular item, you must choose a container that doesn't invalidate its iterators on insertion/removal. std::vector
is obviously not fit for this, but std::list
is.
Your registerHandler
function will just have to return the iterator returned by std::list::insert
, and unregisterHandler
will just be a matter of calling HandlerFunctionList.erase(iteratorToken);
.
The only downside of this implementation is that, unlike Yakk's, it doesn't use a dictionary to store the tokens so it can't check the validity of the token beforehand and things will go wrong if the user passes an invalid iterator to your unregisterHandler
.
However, the upside is increased performance since it avoids the intermediary dictionary altogether.
Choose your poison.