调用QMap内部注册的指针函数

问题描述

我目前正在编写一个程序,该程序需要根据串行设备发送的响应字节调用特定函数。由于命令的数量有点大(约 140 个命令),我决定更简单的方法是使用 QMap 将响应字节与其各自的帧“解释”函数相关联,其创建方式如下:>

class ConfidentialDevice;
typedef void (ConfidentialDevice::*readerFunction_t)(const Frame &frame);
    
class ConfidentialDevice : public QObject {
   // QObject stuff...
    
private:
   // Frame interpretation functions
   void readerFunctionA(const Frame& frame);  
   void readerFunctionB(const Frame& frame);  
   void readerFunctionc(const Frame& frame); 
   // And so on...

   // God-function that calls the other functions depending on frame response byte
   void readFrame(const Frame& frame);
    
   // Registers all frame interpretation functions in the map
   void registerInterpretationFunctions();
    
private:
   // QMap that relates response byte to functions
   QMap<quint8,readerFunction_t> m_functionMap;
};

registerInterpretationFunctions() 的实现如下所示:

void ConfidentialDevice::registerFrameInterpretationFunctions()
{
    // Clear function map
    m_functionMap.clear();

    // Register response functions
    m_functionMap.insert(SECRET_DEVICE_COMMAND_A,&ConfidentialDevice::readerFunctionA);
    m_functionMap.insert(SECRET_DEVICE_COMMAND_B,&ConfidentialDevice::readerFunctionB);
    m_functionMap.insert(SECRET_DEVICE_COMMAND_C,&ConfidentialDevice::readerFunctionC);
    // And so on...
}

到目前为止,一切正常并正确编译。但是,当我想调用m_functionMap注册函数时遇到了问题。目前,我在 readFrame 函数中有此代码

void ConfidentialDevice::readFrame(const Frame &frame)
{
    // Call apropiate frame interpretation function
    if (m_functionMap.contains(frame.command()))
    {
        readerFunction_t fun = m_functionMap.value(frame.command()); // This works
        (*fun)(frame); // <-- I want to call `fun`,but this results in a compilation error
    }
}

我从编译器得到的错误是:

indirection requires pointer operand ('readerFunction_t' (aka 'void (ConfidentialDevice::*)(const Frame &)') invalid)

有什么办法可以解决这个问题吗?对所有命令使用 switch-case 是一种方法,但会导致代码可读性、可维护性和更容易出错。

提前致谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)