我正在尝试创建一个映射来保存可以注册和触发的函数。我似乎不能得到正确的绑定/函数/指针语法来正确地编译它。
这是我所拥有的:我已经尝试了boost::bind和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;
}谢谢你的帮助!
发布于 2013-04-17 04:41:48
typedef boost::function < void (listenArg) > Actions;应该用来代替函数指针。
发布于 2013-04-17 04:41:43
问题是,您告诉编译器Actions是一个非成员函数指针,然后您尝试将boost::function放入该类型的变量中。它们是两个完全不相关的类型,这样的赋值是不可能发生的。相反,您需要使您的Actions类型定义为boost::function<void (listenArg)>。
发布于 2013-04-17 04:44:00
您可以使用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;https://stackoverflow.com/questions/16046623
复制相似问题