简体   繁体   中英

Pass an objects member function as argument (function pointer)

I have a pointer to an object 'eventHandler' which has a member function 'HandleButtonEvents':

I call it like this:

eventHandler->HandleButtonEvents();

Now I want to pass a pointer to the member-function 'HandleButtonEvents()' of the class 'EventHandler' as an argument to another the object 'obj' like in this Stackoverflow example :

ClassXY obj = ClassXY(eventHandler->HandleButtonEvents);

The constructor is declared like this:

ClassXY(void(*f)(void));

The compiler tells me:

error : invalid use of non-static member function

What am I doing wrong?

Using std::function and std::bind as suggested in my comment makes it very easy:

#include <iostream>
#include <functional>

class ClassXY
{
    std::function<void()> function;

public:
    ClassXY(std::function<void()> f)
        : function(f)
    {}

    void call()
    {
        function();  // Calls the function
    }
};

class Handler
{
public:
    void HandleButtonEvent()
    {
        std::cout << "Handler::HandleButtonEvent\n";
    }
};

int main()
{
    Handler* handler = new Handler;

    ClassXY xy(std::bind(&Handler::HandleButtonEvent, handler));

    xy.call();
}

See here for a live example .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM