![](/img/trans.png)
[英]Can I have an array of lambda pointers in order to hold functions with different types of arguments/return values?
[英]Is it possible to hold member functions with different arguments in an array?
假设我有
void a::f1()
void a::f2(int)
void a::f3(const std::string&)
我可以使用数组来存储类似
ary1 = {&a::f1, bind(&a::f2, 2), bind(&a::f3, "abc"}
ary2 = {&a::f1, bind(&a::f3, "def")}
只要可调用对象具有相同的签名,就可以在std::function
存储不同的可调用对象,例如:
struct A {
void f1();
void f2(int);
void f3(const std::string&);
};
int main() {
std::function<void(A&)> functions[] = {
&A::f1
, [](A& a) { a.f2(2); }
, [](A& a) { a.f3("abc"); }
, std::bind(&A::f3, std::placeholders::_1, "abc")
};
A a;
for(auto& f : functions)
f(a);
}
请注意,我在这里使用了lambda表达式而不是std::bind
因为lambda是最佳实践:更容易编写,阅读和更有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.