如何在C++中正确定义调度函数?

发布于 2025-01-28 19:34:13 字数 1175 浏览 2 评论 0原文

我有以下问题:

  1. 我通过af_unix套接字接收命令(网络订购没有问题)。
  2. 数据包中的第一个单词是命令,其余的是“参数”。
  3. 每个命令都有一个定义明确的参数,我编码为struct,命令标识符(uint32_t)作为第一个字段。
  4. 我也有一组处理命令并接受相对struct作为参数的功能。
  5. 我目前有类似的东西:
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: ...
    }
}

由于有很多命令(〜100),这很快变得非常乏味且几乎可以维护。

我考虑过编写std :: map< commands_e,function>,但我不确定这是处理此特定情况的正确方法。

而且,明确的铸造似乎很丑陋。

有人可以指向我的最佳练习吗?

I have the following problem:

  1. I receive commands through an AF_UNIX socket (no problems about network byte ordering).
  2. the first word in packet is the command, the remainder is "parameters".
  3. each command has a well-defined set of parameters I coded as a struct having the command identifier (uint32_t) as the first field.
  4. I also have a set of functions handling the commands and accepting the relative struct as parameter.
  5. 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文