首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在map c++中注册成员函数

如何在map c++中注册成员函数
EN

Stack Overflow用户
提问于 2013-04-17 04:37:42
回答 3查看 978关注 0票数 1

我正在尝试创建一个映射来保存可以注册和触发的函数。我似乎不能得到正确的绑定/函数/指针语法来正确地编译它。

这是我所拥有的:我已经尝试了boost::bind和boost:

代码语言:javascript
复制
#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;
}

谢谢你的帮助!

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-04-17 04:41:48

代码语言:javascript
复制
typedef boost::function < void (listenArg) > Actions;

应该用来代替函数指针。

票数 4
EN

Stack Overflow用户

发布于 2013-04-17 04:41:43

问题是,您告诉编译器Actions是一个非成员函数指针,然后您尝试将boost::function放入该类型的变量中。它们是两个完全不相关的类型,这样的赋值是不可能发生的。相反,您需要使您的Actions类型定义为boost::function<void (listenArg)>

票数 2
EN

Stack Overflow用户

发布于 2013-04-17 04:44:00

您可以使用boost::function模板

代码语言:javascript
复制
#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;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16046623

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档