问题
How would you implement multicast for TR1 functors? I have my callback slots implemented like
void setCallback(std::tr1::function<void (std::string)> cb)
{
this->callback = cb;
}
but need to pass more than one callback in one of them. I don't want to go into more complex solutions like observer, as this is the only case I need multicast so far. I also cannot use Boost.Signals (as suggested here), because I cannot use Boost. I don't need to explicitly handle disabling callback when subscriber no longer exist.
回答1:
You most likely want:
void registerCallback(std::tr1::function<void (std::string)> cb)
{
this->callbacks.push_back(cb);
}
with callbacks
a container (whichever you like) of std::tr1::function
objects instead of a single one. When dispatching, iterate over the callbacks.
Also, if you want to be able to remove callbacks later, you can do something along these lines:
// I use list because I don't want the iterators to be invalid
// after I add / remove elements
std::list<std::function<void(std::string)>> callbacks;
...
typedef std::list<std::function<void(std::string)>>::iterator callback_id;
callback_id register_callback(std::function<void(std::string)> f)
{
return callbacks.insert(callbacks.end(), f);
}
void unregister_callback(callback_id id)
{
callbacks.erase(id);
}
回答2:
Put them in a list / vector. If you have to remove them individually you have to wrap them some how (because they are not comparable).
回答3:
Have a sequence of them rather than a single function (i.e. a vector<...>
), and when calling back, iterate over the sequence and call.
e.g
std::vector<std::tr1::function<void (std::string)> > callbacks;
auto it = callbacks.begin(), end = callbacks.end();
for(; it != end; ++it)
(*it)("somestring");
来源:https://stackoverflow.com/questions/7887582/tr1-function-multicast