
First, the working code: #include <boost/bind.hpp> #include <boost/function.hpp> #include <iostream> #include <string> #include <map> using namespace std; struct message { string mtablename; unsigned long long mpk; message(const string& tablename, const unsigned long long pk) : mtablename(tablename), mpk(pk) { } }; typedef boost::function < void, unsigned long long > MessageFunctor; typedef multimap < string, MessageFunctor > MessageFunctorMap; typedef pair < MessageFunctorMap::iterator, MessageFunctorMap::iterator > MessageFunctorTableMapIteratorPair; void callfunctor(pair < string, MessageFunctor > item, unsigned long long pk) { item.second(pk); } class MessageCenter { MessageFunctorMap mHandlerMap; public: MessageCenter() { } void sendMessage(message& amessage) { MessageFunctorTableMapIteratorPair iterPair = mHandlerMap.equal_range(amessage.mtablename); std::for_each(iterPair.first, iterPair.second, boost::bind (&callfunctor, _1, amessage.mpk)); // QUESTION LINE } void addHandler(string tableName, MessageFunctor handler) { mHandlerMap.insert(make_pair(tableName, handler)); } }; int gFooCounter = 0; void fooHandler(unsigned long long x) { cout << "fooHandler called on pk=" << x << endl; gFooCounter++; } void gooHandler(unsigned long long x){} int main(int argc, const char** argv) { MessageCenter messageCenter; messageCenter.addHandler("foo", fooHandler); messageCenter.addHandler("foo", fooHandler); messageCenter.addHandler("goo", gooHandler); // send some messages message fooMessage("foo", 123); messageCenter.sendMessage(fooMessage); if(gFooCounter != 2) cerr << "something didn't work"; else cout << "everything worked..." << endl; return 0; } now for the question: on the line labeled "QUESTION LINE", you can see that I'm binding to a functor called "callfunctor". All callfunctor does is call the functor embedded in the map's pair. Is there a way to simplify the line in question so that I don't need to create the functor just to get access to the pair.second member? -Darin

Darin Buck wrote: [...]
void callfunctor(pair < string, MessageFunctor > item, unsigned long long pk) { item.second(pk); } [...] void sendMessage(message& amessage) { MessageFunctorTableMapIteratorPair iterPair = mHandlerMap.equal_range(amessage.mtablename); std::for_each(iterPair.first, iterPair.second, boost::bind (&callfunctor, _1, amessage.mpk)); // QUESTION LINE } [...] now for the question:
on the line labeled "QUESTION LINE", you can see that I'm binding to a functor called "callfunctor". All callfunctor does is call the functor embedded in the map's pair.
Is there a way to simplify the line in question so that I don't need to create the functor just to get access to the pair.second member?
I don't see an easier way to accomplish the same effect. You can access pair.second without an additional function object but you'll still have to add one in order to invoke it.
participants (2)
-
Darin Buck
-
Peter Dimov