First of all, I understand how to implement a dispatch table using function pointers and a string or other lookup, that's not the challenge.
What I'm looking for is some way to dynamically add entries to this table at compile time.
The type of code structure I'd hope for is something like:
Strategy.h - contains function definition for the dispatcher and dispatch table definition Strategy.c - contains code for dispatcher
MyFirstStrategy.c - includes Strategy.h and provides one implementation of the strategy MyOtherStrategy.c - includes Strategy.h and provides a second implementation of the stratgy
The idea is that the code to insert function pointers and strategy names into the dispatch table should not live in Strategy.c but should be in the individual strategy implementation files and the lookup table should be somehow dynamically constructed at compile time.
For a fixed size dispatch table, this could be managed as below but I want a dynamically sized table, I don't want the Strategy.c implementation to have to include all of the header files for the implementations and I'd like the dispatch table to be constructed at compile time, not run time.
Fixed Size Example
Strategy.h
typedef void strategy_fn_t(int);
typedef struct {
char *strategyName;
strategy_fn_t *implementation;
} dispatchTableEntry_t;
MyFirstStrategy.h
#include "Strategy.h"
void firstStrategy( int param );
MyOtherStrategy.h
#include "Strategy.h"
void otherStrategy( int param );
Strategy.c
#include "Strategy.h"
#include "MyFirstStrategy.h"
#include "MyOtherStrategy.h"
dispatchTableEntry_t dispatchTable[] = {
{ "First Strategy", firstStrategy },
{ "Other Strategy", otherStrategy }
};
int numStrategies = sizeof( dispatchTable ) / sizeof(dispatchTable[0] );
What I really want is some preprocessor magic which I can insert into the strategy implementation files to handle this automatically e.g.
MyFirstStrategy.c
#include "Strategy.h"
void firstStrategy( int param );
ADD_TO_DISPATCH_TABLE( "First Strategy", firstStrategy );
Any thoughts ?