簡體   English   中英

成員函數回調

[英]Member function callback

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

顯然,它不能注冊成員函數,因為指向成員函數的函數指針對象需要指定類,但是每個類都應該能夠注冊其函數。 std::function<void(Class&)>

使用模板系統,我無法從我假設的靜態類的一個“實例”中訪問所有動作。 如何實現呢?

示例其外觀應為:

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

    void callMe(){}
}

給定成員函數使用其他參數,則需要綁定此參數。 例如,您可以使用以下代碼:

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

bind()表達式將創建一個不帶參數的函數對象。 顯然,對於這種方法, this需要堅持足夠長的時間。

您可以使用std :: bind或lambda函數

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

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

我建議閱讀lambda函數。 非常容易使用,並且比std :: bind功能強大得多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM