Search code examples
c++arraysfunctionfunction-pointerspointer-to-member

How can I create an array of member function pointers coupled with different objects?


Say I have class A with function foo(int i) and class B with function bar(int i), as well as objectA (of class A) and objectB (of class B). I can call the functions like so

objectA.foo(10);
objectB.bar(20);

What I would like to do is have them both as function pointers in an array arr and calling them like so

arr[0](10);
arr[1](20);

Is there a way of doing this in C++? If so, how efficient is it?


Solution

  • You could store std::function objects in a std::vector that you create from lambda functions capturing objectA or objectB. Calling std::function objects comes with a little overhead so if time is critical, you'll have to measure if it's good enough.

    Example:

    #include <functional>
    #include <iostream>
    #include <vector>
    
    struct A {
        void foo(int x) { std::cout << "A::foo " << x << '\n'; }
    };
    
    struct B {
        void bar(int x) { std::cout << "B::bar " << x << '\n'; }
    };
    
    int main() {
        A objectA;
        B objectB;
        std::vector< std::function<void(int)> > arr{
            [&objectA](int x) { objectA.foo(x); },
            [&objectB](int x) { objectB.bar(x); },
        };
        arr[0](10);
        arr[1](20);
    }
    

    Output:

    A::foo 10
    B::bar 20