如果我有两个函数
void foo()
{
std::cout << 1 << std::endl;
}
void bar()
{
std::cout << 2 << std::endl;
}
我有一个函数指针
std::function<void()> v;
我想要打印v()
1
2
最佳答案
std::function
对target的定义是const T* target() const
,也就是说它只能存储一个target。
This question has been asked before ,您所描述的情况在事件处理程序的上下文中在 CLR/.NET 中称为“委托(delegate)多播”。
有几种可能的解决方案:
第一种是使用 lambda 或其他函数手动定义多播:
function<void()> v = []() { foo(); bar(); }; v();
第二个是定义您自己的完整
std::function
-esque,它支持可变数量的目标。您可以使用template
数组(从而避免在运行时使用vector
)...或者只是使用vector
。第三种选择是简单地包装
vector
(警告:可能是伪代码):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 ); } }
用法:
MulticastFunction<void()> mc; mc.addTarget( foo ); mc.addTarget( bar ); mc();
关于c++ - 制作一个指向两个函数的 std::function c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36637847/