我定义了一个类模板,如下所示:
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
)。
这就是为什么你会收到错误并需要强制转换 this
至Derived*
:
(static_cast<Derived*>(this)->*(call))(...);
当然,这仅在 Derived
时有效。实际上源自 Node
类。
关于c++ - 调用指向派生类成员的指针时,指向成员类型与对象类型不兼容的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40265798/