Vector of non-static member pointer functions with this

2893 views c++
1

In C++17, how do you create a vector of non-static member pointer functions with this and subsequently call the functions?

Example.hpp

class Example{
    public:
        Example();

        void function1();
        void function2();
};

Example.cpp (psuedocode)

Example::Example(){
    std::vector<void (*)()> vectorOfFunctions;
    vectorOfFunctions.push_back(&this->function1);
    vectorOfFunctions.push_back(&this->function2);

    vectorOfFunctions[0]();
    vectorOfFunctions[1]();
}

void Example::Function1(){
    std::cout << "Function 1" << std::endl;
}

void Example::Function2(){
    std::cout << "Function 2" << std::endl;
}

answered question

2 Answers

1

You can use std::function instead of pointer to members:

std::vector<std::function<void()>> vectorOfFunctions;

vectorOfFunctions.push_back(std::bind(&Example::function1, this));
vectorOfFunctions.push_back(std::bind(&Example::function2, this));

This allows you to generalize the vector to hold static member functions or other type of functions.

posted this
3

If you want to stick to member function pointer, it should be

std::vector<void (Example::*)()> vectorOfFunctions;
//                ^^^^^^^^^
vectorOfFunctions.push_back(&Example::function1);
vectorOfFunctions.push_back(&Example::function2);

And invoke them like

(this->*vectorOfFunctions[0])();
(this->*vectorOfFunctions[1])();

BTW: As a supplement to Jans's answer, you can also use std::function with lambda, e.g.

std::vector<std::function<void ()>> vectorOfFunctions;
vectorOfFunctions.push_back([this]() { this->function1(); });
vectorOfFunctions.push_back([this]() { this->function2(); });

vectorOfFunctions[0]();
vectorOfFunctions[1]();

posted this

Have an answer?

JD

Please login first before posting an answer.