取模板函数地址,模板以类型为参数,函数是否实例化?

问题描述 投票:0回答:0

CHIP 使用模板函数来编码/解码数据包。 例如 InvokeCommandRequest https://github.com/project-chip/connectedhomeip/blob/master/src/controller/InvokeInteraction.h#L45

这些模板在大型 switch 语句中得到扩展https://github.com/project-chip/connectedhomeip/blob/master/examples/light-switch-app/silabs/common/BindingHandler.cpp#L45 https://github.com/espressif/esp-matter/blob/main/components/esp_matter/esp_matter_client.cpp#L210

我更愿意在代码的另一个地方获取这些函数的地址,然后将它们传递到一个公共例程中。

    LevelControl::Commands::MoveWithOnOff::Type commandDataT;
    commandDataT.moveMode = (position == UP ? EMBER_ZCL_MOVE_MODE_UP : EMBER_ZCL_MOVE_MODE_DOWN);
    commandDataT.rate.SetNonNull(250);

    const decltype(&Controller::InvokeCommandRequest<chip::app::Clusters::LevelControl::Commands::MoveWithOnOff::Type>) invoke_address =
        &Controller::InvokeCommandRequest<chip::app::Clusters::LevelControl::Commands::MoveWithOnOff::Type>;

call common_routine(&commandDataT, invoke_address)

换句话说,将 invoke_address 传递到一个通用函数中,这样我就可以避免这样的 switch 语句: https://github.com/project-chip/connectedhomeip/blob/master/examples/light-switch-app/silabs/common/BindingHandler.cpp#L45 通过一次调用 invoke_address(....) 替换开关。匹配的结构也将与函数地址一起传递。

这能做到吗?

c++ templates function-pointers member-functions addressof
© www.soinside.com 2019 - 2024. All rights reserved.