我想創建一個地圖來保存可以註冊和解僱的功能。我似乎無法得到正確的綁定/函數/指針語法,以便正確地進行編譯。如何註冊成員函數在地圖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'而不是原始函數指針。 –
對於你的問題很重要的是,你似乎想要保存*成員函數*和*調用對象。 –