c++ - Calling a functor in a std::map with boost::bind -


i having trouble this, , couldn't find solution on so. took me while figure out thought i'd post it, in case useful else

problem: have set of functors of different types, want store in std::map , call later sort of switch statement/factory.

class foo { public:     void operator() (int x) {         std::cout << "in foo" << x << std::endl;     } }; class bar { public:     void operator() (int x) {         std::cout << "in bar" << x << std::endl;     } }; 

the map looks like

std::map<int,boost::function<void(int)>> maps; 

and inserts like

maps.insert(std::make_pair(1,boost::bind(&foo::operator(),foo(),_1))); 

and can call like

auto iter = maps.find(1); iter->second(123); 

looking @ solution it's quite simple 1 liner, compared mental gymnastics trying figure out - oh :)

what trying store boost::signals2::signal objects chain set of factories,in map, never did figure out. question, how store instead in map?

std::map<std::string,boost::signals2::signal<void(int)>> m_factory; // create object want store boost::signals2::signal<void(int)> sig; sig.connect(foo()); // fails m_factory.insert(std::make_pair("blah",sig)); 

but get

std::pair<_ty1,_ty2> std::_tree<_traits>::insert(std::pair<const _kty,_ty> &&)' : cannot convert parameter 1 'std::pair<_ty1,_ty2>' 'std::pair<_ty1,_ty2> && 

edit simplified example further

edit 2 - fix bug declared map reference

further this, seems work fine

typedef boost::signals2::signal<void(int)> signal; m_factory["blah"] = signal().connect(foo()); 

which thought logically same make_pair?

boost::signals non-copyable, makes them not suitable used std containers. should use pointers (possibly smart pointers) signal in

typedef boost::signals2::signal<void(int)> sig; typedef std::shared_ptr<sig> psig; typedef std::map<int, psig> map_sig;  void f(int){}  int main(){     psig s(new sig);     s->connect(f);      map_sig m;     m.insert( map_sig::value_type(1, s) ); } 

(you can try code here).


Comments

Popular posts from this blog

curl - PHP fsockopen help required -

HTTP/1.0 407 Proxy Authentication Required PHP -

c# - Resource not found error -