user3684240
user3684240

Reputation: 1590

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!

Upvotes: 1

Views: 112

Answers (2)

pmr
pmr

Reputation: 59841

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);

Upvotes: 2

sehe
sehe

Reputation: 393934

You need to bind it:

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

Upvotes: 0

Related Questions