是否可以在数组中保存具有不同参数的成员函数?

Is it possible to hold member functions with different arguments in an array?

本文关键字:参数 成员 函数 数组 保存 是否      更新时间:2023-10-16

假设我有

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 是最佳实践:更易于编写、阅读和更高效。