0

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")}
gsamaras
  • 71,951
  • 46
  • 188
  • 305
Arthur Cheuk
  • 115
  • 1
  • 1
  • 7

1 Answers1

3

It is possible to store different callable objects in std::function as long as the callables have the same signature, e.g.:

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.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271