我想创建一个地图来保存可以注册和解雇的功能。我似乎无法得到正确的绑定/函数/指针语法,以便正确地进行编译。如何注册成员函数在地图c + +
这里是我:我曾经尝试都的boost ::绑定和提升:
#include <cstdlib>
#include <iostream>
#include <boost/bind/bind.hpp>
#include <boost/function.hpp>
#include <map>
using namespace std;
typedef const std::string& listenArg;
typedef void (*Actions)(listenArg str);
std::multimap<int, Actions> functions;
// fire in the hole!
void fire(int methods, listenArg arg0) {
std::multimap<int, Actions>::iterator function = functions.find(methods);
typedef std::pair<int, Actions> pear;
for (function = functions.begin(); function != functions.end(); ++function) {
(*(function->second))(arg0);
}
}
void listen1(listenArg arg0) {
std::cout << "listen1 called with " << arg0 << std::endl;
}
class RegisteringClass {
public:
RegisteringClass();
virtual ~RegisteringClass();
void callMeBaby(listenArg str) {
std::cout << "baby, i was called with " << str << std::endl;
}
};
int main(int argc, char** argv) {
const int key = 111;
functions.insert(make_pair<int, Actions>(key, listen1));
fire(key, "test");
// make a registeringClass
RegisteringClass reg;
// register call me baby
boost::function<void (listenArg) >
fx(boost::bind(&RegisteringClass::callMeBaby, reg, _1));
//std::bind(&RegisteringClass::callMeBaby, reg, _1);
functions.insert(
make_pair<int, Actions> (key, fx));
// fire
fire(key, "test2");
return 0;
}
感谢您的帮助!
无论'的boost :: function'也不'提振:: bind'的结果类型可以转化为函数指针。将'Actions'类型定义为'boost :: function'而不是原始函数指针。 –
对于你的问题很重要的是,你似乎想要保存*成员函数*和*调用对象。 –