On Thursday I was helped by a co-worker to look more closely into boost::bind and boost::function. Its just awesome what you can do with these two together. Say you are writing a library which intends to provide a thread-safe way of accessing a certain structure (ElementType) for the users of your library. In a typical case you would have a container that contains some n objects of ElementType and you want the user to be able to iterate over these. A cool way to do this is to let the user pass a function delegate for your API to call within the thread-safety semantics of your library code. For instance if you had a container ElementContainer every access to which was made thread-safe using an ACE_Guard with a local mutex variable, then you can provide the users of your library an element visitor something to the effect of:
typedef boost::function1 <> ElementVisitor;
and then provide a public API function:
bool VisitElements(const Key& key, const ElementVisitor& visitor);
What the above psuedo-code does is it provides the user a way to iterate thru' the ElementContainer (which contains objects of ElementType) in a thread-safe way that's transparent to the user using a key to find which elements to iterate over. All the user needs to do is instantiate an ElementVisitor delegate which takes the ElementType as a const ref argument and do his mumbo jumbo inside the delegate which would be called inside the context of the library.
But the magic only begins here. boost::bind can be used to tie any random caller function to the ElementVisitor. And club this with boost::ref and boost::cref, you can also have multiple return types in the caller functions. For instance let's say the user of the library has a function as below:
void UsersClass::ElementVisitorFunc(uint32_t arg1, uint32_t arg2, const ElementType& elem);
this can be bound to the ElementVisitor as below:
ElementVisitor del = boost::bind(&UsersClass::ElementVisitorFunc, this, arg1, arg2, _1);
Whats magical about this is although to the caller this is a function call with three arguments, to the library that provides a thread-safe API to visit and access the contained ElementType objects, its a function call with a single argument of type const ElementType&.
Just awesomeness throughout. Thanks DJ and KR for introducing me to this wonderful visitation technique.
Sifar.
No comments:
Post a Comment