Boost logo

Boost :

From: Dean Michael Berris (mikhailberis_at_[hidden])
Date: 2006-06-08 19:49:35


On 6/8/06, Peter Dimov <pdimov_at_[hidden]> wrote:
> Dean Michael Berris wrote:
>
> > //set up a registry
> > dispatch::dispatcher<void (), int> callbacks;
> >
> > // register a nullary free function f to index 0
> > callbacks[0] = f;
> >
> > // bind arguments to a single argument function p to index 1
> > callbacks[1] = boost::bind(p, 1);
> >
> > // get user input then execute appropriate callback
> > int i;
> > cin >> i;
> > callbacks[i]();
>
> This can be done with map< int, function<void()> >.

Yes, this is just one of the things that the dispatcher can do. The
current implementation (lacking documentation) can be downloaded from
http://tinyurl.com/px33v -- there are a few other uses, including a
means for defining a strategy for index validation. An example of this
usage is shown below (and can also be seen from the unit test):

#include <iostream>
#include "dispatch.hpp"

int function_returns_int (int j) {
        return j+1;
};

struct require_even_strategy {
        bool operator() (int number) const {
                return (number != 0) && ((number % 2) == 0);
        };
};

typedef dispatch::dispatcher<int(), int, require_even_strategy,
std::vector> dispatcher_t;

int main(int argc, char **argv) {
  dispatcher_t d;
  d[2] = boost::bind(function_returns_int, 3);
  d[4] = boost::bind(function_returns_int, 5);
  dispatcher_t::collection_type v = d.dispatch(2);
  std::cout << v[0] << ", " << v[1] << std::endl;
  return 0;
}

Future direction is support for asynchronous and thread safe
invocations of operator[] and dispatch().

It does implement some of the Boost.Signals functionality in the
dispatch() call, but (though I certainly haven't tried yet) I'd think
it will work well with signals too.

And yes, the dispatcher holds an std::map of wrappers to
boost::function<> instances.

-- 
Dean Michael C. Berris
C/C++ Software Architect
Orange and Bronze Software Labs
http://3w-agility.blogspot.com/
http://cplusplus-soup.blogspot.com/
Mobile: +639287291459
Email: dean [at] orangeandbronze [dot] com

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk