简体   繁体   中英

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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