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

Time:11-29

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?

CodePudding user response:

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

CodePudding user response:

Similar to @ted-lyngmo's answer, but with C 20, you can also use std::bind_front to create the function object for the vector:

int main()
{
    A objectA;
    B objectB;
    std::vector<std::function<void(int)>> arr{
        std::bind_front(&A::foo, objectA),
        std::bind_front(&B::bar, objectB)
    };
    arr[0](10);
    arr[1](20);
}

Godbolt

  • Related