1

If I have two functions

void foo()
{
    std::cout << 1 << std::endl;
}

void bar()
{
    std::cout << 2 << std::endl;
}

and I have a function pointer

std::function<void()> v;

and I want v() to print

1
2
Dai
  • 141,631
  • 28
  • 261
  • 374
Ace shinigami
  • 1,374
  • 2
  • 12
  • 25

1 Answers1

5

std::function's definition of target is const T* target() const, which means it can only store one target.

This question has been asked before, the situation you're describing is known as "delegate multicasting" in CLR/.NET in the context of event-handlers.

There are a few possible solutions:

  1. The first is to use a lambda or other function to define the multicast manually:

    function<void()> v = []() {
        foo();
        bar();
    };
    v();
    
  2. The second is to define your own full std::function-esque which supports a variable number of targets. You could do it with a template array (thus avoiding runtime use of vector)... or just use a vector anyway.

  3. A third option is to simply wrap vector anyway (warning: pseudocodeish):

    template<class FuncType>
    class MulticastFunction {
    private:
        vector<std::function<FuncType>> targets;
    public:
        void operator()() {
            for(auto& target : this->targets) {
                target();
            }
        }
        void addTarget(FuncType& target) {
            this->targets->push_back( target );
        }
    }
    

    Usage:

    MulticastFunction<void()> mc;
    mc.addTarget( foo );
    mc.addTarget( bar );
    mc();
    
Community
  • 1
  • 1
Dai
  • 141,631
  • 28
  • 261
  • 374
  • You probably want `target` to be by value or const ref, so it can bind to lambdas for example – M.M Apr 15 '16 at 04:53