2013-04-16 15 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;