1

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?

1
  • 1
    @Ted Lyngmo Sorry, forgot! Commented Nov 29, 2021 at 13:37

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Though this will copy objects of type A and B - could be a good thing if you need the closure functions to live longer than objectA and objectB, or bad if you need the calls to use the original objects. To tell it not to copy, we could do std::bind_front(&A::foo, std::ref(objectA)), std::bind_front(&B::bar, std::ref(objectB))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.