微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决调用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 举报,一经查实,本站将立刻删除。