Switching from Pointer to Member Functions in C++

  • C++
  • 1 min read

This tutorial shows how to do switch from pointer to member functions in C++ through an example.

Example: Pointer to Member functions in C++

Suppose you want to do is a "switch" using a function pointer, but using the method pointers. This can be done using std::invoke from <functional> header in C++ (2017).

#include <iostream>
#include <functional>

class A
{
    using RunPtr = void(A::*)(int);
    // or with typedef
    // typedef void(A::*RunPtr)(int);
    RunPtr RunMethod;

public:
    void SetOn(bool value)
    {
        RunMethod = value ?  &A::RunOn : &A::RunOff;
    }

    void  Run(int arg)
    {
        std::invoke(RunMethod, this, arg);
        // do something...
    }

    void RunOn(int arg) { std::cout << "RunOn: " << arg << "\n"; }

    void RunOff(int arg) { std::cout << "RunOff: " << arg << "\n";  }
};

int main()
{
    A obj;
    obj.SetOn(true);
    obj.Run(1);       // prints: RunOn: 1  
    obj.SetOn(false);
    obj.Run(0);       // prints: RunOff: 0
}

Output:

RunOn: 1
RunOff: 0

See also: