Aleph-w 3.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
ah-dispatcher.H File Reference

Command dispatcher pattern implementation. More...

#include <iostream>
#include <tpl_dynMapTree.H>
Include dependency graph for ah-dispatcher.H:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Classes

class  AHDispatcher< Key, Operation >
 Tree-based command dispatcher. More...
 
class  AhHashDispatcher< Key, Operation >
 Hash-based command dispatcher. More...
 
struct  AhHashDispatcher< Key, Operation >::Equal
 

Detailed Description

Command dispatcher pattern implementation.

This file provides two dispatcher classes that map keys to callable operations, enabling dynamic command dispatching based on runtime keys.

Overview

A dispatcher is a registry that associates keys with operations (functions, lambdas, or function objects). At runtime, you can execute an operation by providing its key. This is useful for:

  • Command-line argument handling
  • Event-driven systems
  • Plugin architectures
  • State machines
  • Menu systems

Available Dispatchers

Class Backing Store Lookup Time
AHDispatcher DynMapTree (balanced tree) O(log n)
AhHashDispatcher ODhashTable (hash table) O(1) average

Usage Example

#include <ah-dispatcher.H>
#include <functional>
// Define operations
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
// Create dispatcher with string keys and function pointers
AHDispatcher<std::string, int(*)(int, int)> calc;
calc.insert("add", add);
calc.insert("sub", sub);
// Execute operations by key
int result = calc.run("add", 5, 3); // returns 8
// Check if key exists
if (calc.valid_key("mul"))
calc.run("mul", 2, 3);
Command dispatcher pattern implementation.
Tree-based command dispatcher.
void insert(const Key &key, Operation op)
Register a key-operation pair.

With Lambdas

using Op = std::function<void(const std::string&)>;
menu.insert("help", [](const std::string&) {
std::cout << "Available commands: help, quit\n";
});
menu.insert("quit", [](const std::string&) {
exit(0);
});
menu.run("help", "");
auto run(const Key &key, Args &&... args) const
Execute the operation associated with a key.
See also
DynMapTree Tree-based map for AHDispatcher
ODhashTable Hash table for AhHashDispatcher
Author
Leandro Rabindranath León

Definition in file ah-dispatcher.H.