Search code examples
c++oopc++11boostboost-signals2

How to implement a class member pointer in C++ using std::function or Boost?


I want to implement an object-oriented function pointer in C++ (comparable to delegates in C#).

I wrote an example code which uses "MagicFunctionPainter" as a placeholder for the final class:

class A
{
public: 
    MagicFunctionPointer p;
    void fireEvent()
    {
         p();
    }
};

class B
{
public:
    void init(A* a)
    {
        a->p = &onEvent;
    }
    void onEvent()
    {
        // in a real-world app, it'd modify class variables, call other functions, ...
    }
};

Does std::function or Boost::Signals2 support that? Are there any other librarys that support that case?

Thank you in advance!


Solution

  • The type of p should be:

    std::function<void(void)> // a function taking no arguments, returning nothing
    

    Create an object of this type in B::init with:

    std::bind(&B::onEvent, this);