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

123 views Asked by At

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!

2

There are 2 answers

3
pmr On BEST ANSWER

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);
0
sehe On

You need to bind it:

 boost::bind(&ClassX::member_function, boost::ref(instance))