简体   繁体   English

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

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

Suppose I have 假设我有

void a::f1()
void a::f2(int)
void a::f3(const std::string&)

Is it possible for me to use an array to store something like 我可以使用数组来存储类似

ary1 = {&a::f1, bind(&a::f2, 2), bind(&a::f3, "abc"}
ary2 = {&a::f1, bind(&a::f3, "def")}

It is possible to store different callable objects in std::function as long as the callables have the same signature, eg: 只要可调用对象具有相同的签名,就可以在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);
}

Note that I used lambda expressions here instead of std::bind because lambdas are the best practice: easier to write, read and more efficient. 请注意,我在这里使用了lambda表达式而不是std::bind因为lambda是最佳实践:更容易编写,阅读和更有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM