c++ - 调用指向派生类成员的指针时,指向成员类型与对象类型不兼容的指针

标签 c++ templates derived-class pointer-to-member

我定义了一个类模板,如下所示:

template <const category_id_t category, class Base>
class Node : public Base
{
...
    template <typename Derived, class T>
    void on_message( const frame_t& frame, void (Derived::*call)(const T*) )
    {
        if ( frame.length == sizeof(T) )
            (this->*(call))((T*)frame.data);
    }
}

论点category用作实现几个相似类并根据特定类别提供适当特化的 token 。然后派生出上面的类:

template <class Base>
class Sys : public Node<CID_SYS, Base>
{
    Sys() : Node<CID_SYS, Base>() { /* ... */ }
    ....
};

Sys只是一个为类别 CID_SYS 的对象提供基接口(interface)的类(枚举,值 = 5)并用作接口(interface)实际实现的基类:

class SysImpl : public Sys<CAN>
{
    ...
    /* Parse remote notifications */
    void on_notify( const state_info_t* ) { /* ... */ }
};

SysImpl sys;

最后我有一个调用基类 Node<CID_SYS, Base> 的函数成员函数on_message()像这样:

void foo(const frame_t& frame)
{ sys.on_message(frame, &SysImpl::on_notify ); }

编译器在 (this->*(call))((T*)frame.data) 行周围抛出错误说

error: pointer to member type 'void (SysImpl::)(const state_info_t*)' is incompatible with object type 'Node<(category_id_t)5u, CAN>'

编译器已成功猜测要调用哪个模板函数,只是它似乎没有“识别”this来自派生类。

我想要调用从 Node<CID_SYS, CAN> 派生的类的任何成员函数,不仅仅是独立函数(到目前为止运行得很好,上面的摘录中没有显示)。

我错过了什么?

最佳答案

on_message函数变量 this不是指向 SysImpl 的指针,它的类型是Node<CID_SYS, CAN>*Node模板类没有成员 on_notify所以你不能在 Node 的实例上调用它。必须在 Derived 的实例上调用它(应该是 SysImpl )。

这就是为什么你会收到错误并需要强制转换 thisDerived* :

(static_cast<Derived*>(this)->*(call))(...);

当然,这仅在 Derived 时有效。实际上源自 Node类。

关于c++ - 调用指向派生类成员的指针时,指向成员类型与对象类型不兼容的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40265798/

相关文章:

c++ - 使用运算符 [] 访问字符串类

c++ - C 代码中 C++ 代码中的 sizeof 类作为编译时常量

c++ - dijkstra 算法的优先级队列

c++ - 在 C++ 中创建派生类

c++ - 在派生类中使用 protected 说明符

c++ - 为什么 'virtual' 对于派生类中的重写方法是可选的?

c++ - Windows 窗体 - 按钮点击

c++ - 检查类是否派生自模板类

c++ - 模板和 typedef 错误

c++ - 在模板类中使用嵌套的嵌套类时,“依赖名称不是类型”