|
Boost Users : |
From: Darin Buck (dbuck_at_[hidden])
Date: 2003-05-22 14:08:53
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
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net