[英]How to pass a member function as an argument?
I have the following Classes:我有以下课程:
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);
};
I want to be able to pass DataStorage::load to EventManager::subscribe so i can call it later on.我希望能够将 DataStorage::load 传递给 EventManager::subscribe,以便稍后调用它。 How can i achieve this in c++?
我怎样才能在 c++ 中实现这一点?
The best way to do this would be with an std::function
:最好的方法是使用
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
Then, to accept a function, you need simply need to do the same thing as before:然后,要接受 function,您只需要像以前一样做同样的事情:
void subscribe(std::string event_type, myFunction handler);
// btw: could just as easily be called ScriptFunction I suppose
Now the tricky part;现在是棘手的部分; to pass a member function, you actually need to bind an instance of
DataStorage
to the member function.要传递成员 function,实际上需要将
DataStorage
的实例绑定到成员 function。 That would look something like this:看起来像这样:
DataStorage myDataStorage;
EventManager manager;
manager.subscribe("some event type", std::bind(&DataStorage::load, &myDataStorage));
Or, if you're inside a member function of DataStorage
:或者,如果您在
DataStorage
的成员 function 中:
manager.subscribe("some event type", std::bind(&DataStorage::load, this));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.