制作一个std :: funtion如果我有两个功能 void foo() { std::cout << 1 << std::endl; } void bar() { std::cout << 2 << std::endl; }
void foo() { std::cout << 1 << std::endl; } void bar() { std::cout << 2 << std::endl; }
指向两个函数C++
问题描述:
std::function<void()> v;
,我想v()
打印
1
2
答
std::function
对目标的定义是const T* target() const
,这意味着它只能存储一个t ARGET。
This question has been asked before,您所描述的情况在事件处理程序的上下文中称为CLR/.NET中的“委托多点传送”。
有几个可能的解决方案:
-
第一种方法是使用lambda或其他功能来定义手动组播:
function<void()> v = []() { foo(); bar(); }; v();
第二是定义自己的全
std::function
-esque支持可变数量的目标。您可以使用template
阵列(因此避免运行时使用vector
),或者只是使用vector
。-
第三种选择是简单地包裹
vector
反正(警告: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); } }
用法:
MulticastFunction<void()> mc; mc.addTarget(foo); mc.addTarget(bar); mc();
+0
您可能希望'target'是通过value或const ref引用的,因此它可以绑定到lambda表达式 –
使用lambda?你的问题是什么? – hyde
@hyde这样就是'[](){foo(); bar();}'对吗? – Julian
如果返回类型是* not *'void',你会期望什么? – o11c