我有以下类(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/