简体   繁体   中英

Member function callback

Present is a class to register functions as callbacks.

class Action {
private:
    static std::multimap<std::string, std::function<void()>> actions;
public:
    static void registerAction(const std::string &key, std::function<void()> action);
}

Obviously it can not register member functions, as function pointer objects to member functions require the class to be specified, but every class should be able to register their functions. std::function<void(Class&)>

Using a template system, I couldn't access all actions from one "instance" of the static class I suppose. How could this be realized?

Example how it should look like:

class B {
public:
    B() {
        Action::registerAction("some_action", &callMe);
    }

    void callMe(){}
}

Given that member functions taken an additional argument, you need to bind this argument. For example, you could use something like this:

Action::registerAction("come_action", std::bind(&callMe, this));

The bind() expression will created a function object taking no arguments. Obviously, for this approach to work, this needs to stick around long enough.

you could use std::bind or a lambda function

// std::bind
Action::registerAction( "bla", std::bind(&callMe, this) );

// lambda
Action::registerAction( "bla", [this]() { this->callMe(); } );

i would suggest reading up on lambda functions. Pretty easy to use, and much more powerful than std::bind.

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