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
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
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:
The first is to use a lambda or other function to define the multicast manually:
function<void()> v = []() {
foo();
bar();
};
v();
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.
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();