我有以下课程:
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 ++中实现这一目标?
答案 0 :(得分:1)
最好的方法是使用std::function
:
tup
然后,要接受一个功能,您只需要做与以前相同的事情即可:
#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
现在棘手的部分;要传递成员函数,实际上您需要bind void subscribe(std::string event_type, myFunction handler);
// btw: could just as easily be called ScriptFunction I suppose
的实例到成员函数。看起来像这样:
DataStorage
或者,如果您位于DataStorage myDataStorage;
EventManager manager;
manager.subscribe("some event type", std::bind(&DataStorage::load, &myDataStorage));
的成员函数中:
DataStorage