'Execute arbitrary function pointer

Im interested in creating arrays of functions which don't take arguments and don't return anything.

Is there a way to create a generic function pointer and execute it?

Example:

ptr ptrArray[1];
PtrArray[0] = &myfunc;

More generally does this work if myfunc is a method in a specifc object? Part of me assumes not since functions are shared across multiple objects in code.

For example, you have a list of objects all with an update method, you want each one executed.



Solution 1:[1]

std::function seems a way to go, as it supports the largest variety of function objects, including lambdas, ones created by bind etc.

#include <functional>
#include <iostream>
#include <array>

struct S
{
    void doStuff() {std::cout << "DoStuffMember " << this << "\n";}
    void doStuff() const {std::cout << "DoStuffMemberConst " << this << "\n";}
};

void doStuff() {std::cout << "DoStuffFree\n";}

int main()
{
    S s;
    std::string_view sv{"local var\n"};
    std::array<std::function<void()>, 8> fkns;
    fkns[0] = [&s]{ s.doStuff();};
    fkns[1] = [&sr=std::as_const(s)]{sr.doStuff();};
    fkns[2] = std::bind<void (S::*)()>(&S::doStuff, s);
    fkns[3] = std::bind<void (S::*)()>(&S::doStuff, std::ref(s));
    fkns[4] = std::bind<void (S::*)() const>(&S::doStuff, std::cref(s));
    fkns[5] = [sv]{std::cout << "lambda capturing " << sv;};
    fkns[6] = []{std::cout << "lambda\n";};
    fkns[7] = doStuff;

    for (auto&& f: fkns) {
        f();
    }

    return 0;
}

Demo

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 alagner