0

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.

Community
  • 1
  • 1
Adam Trhon
  • 2,835
  • 1
  • 19
  • 49

3 Answers3

3

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);
}
Alexandre C.
  • 53,934
  • 10
  • 121
  • 192
0

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");
David Rodríguez - dribeas
  • 198,982
  • 21
  • 284
  • 478
Nim
  • 32,645
  • 2
  • 59
  • 99
0

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).

Simon
  • 1,456
  • 8
  • 11