minow@mountn.dec.com (Martin Minow) (10/09/90)
One of my standard programming methods for dealing with keyword-selected functions is to define a table such as typedef struct { char *name; void (*function)(void); } TABLE; TABLE table[] = { { "up", go_up }, { "down", go_down }, { NULL, NULL } }; This is accessed by code such as for (tp = table; tp->name != NULL; tp++) { if (strcmp(tp->name, request) == 0) { (*tp->function)(); goto found; } } error("Not found\n"); Suppose the function is really a Think C class method. I.e., I have struct MyObject : CObject { void go_up(void); void go_down(void); }; How do I declare the TABLE and function call? The compiler rejects the obvious declarations. It's not an emergency, I built an ugly work-around using some new capabilities of the ANSI-C pre-processor: #define EXPAND_NAMES \ DEF(up) \ DEF(down) #define DEF(what) \ k ## what, enum { EXPAND_NAMES kDummyNameWithoutTrailingComma }; #undef DEF ... struct MyObject : CObject { ... #define DEF(what) void what ## Handler(void); EXPAND_NAMES #undef DEF }; ... char *commands[] { #define DEF(what) #what, EXPAND_NAMES #undef DEF NULL }; Now, the selection is just a switch statement: for (i = 0; commands[i] != NULL; i++) { if (strcmp(commands[i], request) == 0) { switch (i) { #define DEF(what) \ case k##what: MyObject->what ## Handler(); break; EXPAND_NAMES #undef DEF } goto found; } } Any better ideas? Martin Minow minow@bolt.enet.dec.com