2013-04-16 16 views
0

我想創建一個地圖來保存可以註冊和解僱的功能。我似乎無法得到正確的綁定/函數/指針語法,以便正確地進行編譯。如何註冊成員函數在地圖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; 
} 

感謝您的幫助!

+1

無論'的boost :: function'也不'提振:: bind'的結果類型可以轉化爲函數指針。將'Actions'類型定義爲'boost :: function'而不是原始函數指針。 –

+0

對於你的問題很重要的是,你似乎想要保存*成員函數*和*調用對象。 –

回答

4
typedef boost::function < void (listenArg) > Actions; 

應該用來代替函數指針。

+0

完美!謝謝您的幫助。 – brendon

2

問題是您告訴編譯器Actions是非成員函數指針,然後嘗試將boost::function放入該類型的變量中。他們是兩個完全不相關的類型,這樣的任務不可能發生。您需要將Actions typedef改爲boost::function<void (listenArg)>

1

可以使用boost::function模板

#include <cstdlib> 
#include <iostream> 
#include <boost/bind/bind.hpp> 
#include <boost/function.hpp> 
#include <map> 

using namespace std; 

typedef const std::string& listenArg; 

typedef boost::function < void (listenArg) > Actions; 
std::multimap<int, Actions> functions;