简体   繁体   English

成员函数回调

[英]Member function callback

Present is a class to register functions as callbacks. Present是一个将函数注册为回调的类。

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. bind()表达式将创建一个不带参数的函数对象。 Obviously, for this approach to work, this needs to stick around long enough. 显然,对于这种方法, this需要坚持足够长的时间。

you could use std::bind or a lambda function 您可以使用std :: bind或lambda函数

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

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

i would suggest reading up on lambda functions. 我建议阅读lambda函数。 Pretty easy to use, and much more powerful than std::bind. 非常容易使用,并且比std :: bind功能强大得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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