'How to correctly define a dispatching function in C++?
I have the following problem:
- I receive commands through an
AF_UNIXsocket (no problems about network byte ordering). - the first word in packet is the command, the remainder is "parameters".
- each command has a well-defined set of parameters I coded as a
structhaving the command identifier (uint32_t) as the first field. - I also have a set of functions handling the commands and accepting the relative
structas parameter. - I currently have something like:
typedef enum {
Command_a = 0x########,
Command_b = 0x########,
...
} Commands_e;
typedef struct {
uint32_t command;
whatever_t param1;
somethingelse_t param2;
} ParamCommand_a_t;
typedef struct {
uint32_t command;
bool param1;
} ParamCommand_b_t;
...
// forward declarations
void handleCommand_a(ParamCommand_a_t &);
void handleCommand_b(ParamCommand_b_t &);
...
void dispatch(uint32_t *frame) {
switch ((Commands_e)*frame) {
case Command_a: handleCommand_a(*(ParamCommand_a_t *)frame); break;
case Command_a: handleCommand_b(*(ParamCommand_b_t *)frame); break;
...
default: ...
}
}
Since there are a lot of commands (~100) this quickly becomes very tedious and hardly maintainable.
I thought about writing a std::map<Commands_e, function>, but I'm unsure this is the right way to handle this specific case.
Also, the explicit casting seems very ugly.
Can someone point me to best practice?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
