Runtime Dynamic Dispatch

PrevUpHomeNext

Quick Start

The simplest way to use the dispatcher is to register free nullary functions. This is done using the following code snippet:

#include <boost/dispatch.hpp>
#include <iostream>

void function() {
    std::cout << "Function called!" << std::endl;
}

int main (int argc, char * argv[]) {
    boost::dispatch::dispatcher < void () > d;
    d[0] = function;
    d[0] ();
    return 0;
}

This doesn't do much, except register function() to the index 0 of the dispatcher d and invokes it. The following shows a bit more useful example:

#include <boost/dispatch.hpp>
#include <iostream>

void odd() {
    std::cout << "Number is odd!" << std::endl;
}

void even() {
    std::cout << "Number is even!" << std::endl;
}

int main (int argc, char * argv[]) {
    boost::dispatch::dispatcher < void () > d;
    d[0] = even;
    d[1] = odd;
    int input;
    
    while (!std::cin.eof()) {
     std::cin >> input;
     d[input % 2] ();
    }
 
 return 0;
}

The above example shows you that the function calls are determined in runtime based on actual runtime values. This looks like a switch replacement, but there is an added avantage over switch : it allows you to define the type of the index and not be limited to integral types.

This is shown in the example below:

boost::dispatch::dispatcher < void (), std::string > d;

// register the handlers...
d["0"] = function_zero;
d["1"] = function_one;

// ...
std::string input;

while (!std::cin.eof()) {
    std::cin >> input;
    
    try {
        d[input] ();
    } catch (boost::dispatch::unregistered_handler &) {
     std::cout << "Unhandled input!" << std::endl;
    };
}

The important part of the code is the instantiation of the dispatcher which reads boost::dispatch::dispatcher<void(),std::string>d; making a dispatcher which accepts functions that return void and takes no arguments, mapped to a std::string.

The template parameters of dispatcher defines the function signature of the type of functions that can be registered to the dispatcher, and the type of the index to use to map functions to -- in the respective order.
Copyright 2006 ,2007 Dean Michael Berris

PrevUpHomeNext