c++ - 如何将成员函数作为参数传递?

标签 c++

我有以下类(class):

typedef void (*ScriptFunction)(void);
typedef std::unordered_map<std::string, std::vector<ScriptFunction>> Script_map;

class EventManager
{
public:

    Script_map subscriptions;

    void subscribe(std::string event_type, ScriptFunction handler);
    void publish(std::string event);

};

class DataStorage
{
    std::vector<std::string> data;
public:

    EventManager &em;

    DataStorage(EventManager& em);
    void load(std::string);
    void produce_words();


};
DataStorage::DataStorage(EventManager& em) : em(em) {
    this->em.subscribe("load", this->load);     
};

我希望能够将 DataStorage::load 传递给 EventManager::subscribe,以便稍后调用它。我如何在 C++ 中实现这一点?

最佳答案

最好的方法是使用 std::function :

#include <functional>

typedef std::function<void(std::string)> myFunction;
// Actually, you could and technically probably should use "using" here, but just to follow
// your formatting here

然后,要接受一个函数,您只需要像以前一样做同样的事情:

void subscribe(std::string event_type, myFunction handler);
// btw: could just as easily be called ScriptFunction I suppose

现在是棘手的部分;要传递一个成员函数,你实际上需要 bind DataStorage 的实例到成员函数。这看起来像这样:

DataStorage myDataStorage;
EventManager manager;

manager.subscribe("some event type", std::bind(&DataStorage::load, &myDataStorage));

或者,如果您在 DataStorage 的成员函数内:

manager.subscribe("some event type", std::bind(&DataStorage::load, this));

关于c++ - 如何将成员函数作为参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58585319/

相关文章:

c++ - std::deque 的线程安全

c++ - 让基于 makefile 的 cmake 项目在环境变量更改时自动运行 make rebuild_cache

c++ - 未找到来自共享库的符号,但已定义

c++ - 在 C++ 中实例化类的所有不同方法是什么?

c++ - 类静态变量初始化顺序

c++ - 将内部变量传递给结构构造函数 C++

c++ - 使用迭代器时出现编译错误 : "error: ‘...::iterator’ has no member named '...' "

c++ - GMock : EXPECT_CALL not called as expected for File *

c++ - 打开/关闭 handle 时会发生什么?

C++:如何存储一组排序的元组?