Search code examples
c++functortr1

TR1 function multicast


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.


Solution

  • 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);
    }