我正在尝试使用带有 Qt 信号/插槽机制的静态多态性而不是动态多态性。但我得到编译错误。我的代码有什么问题?什么是解决方法?
设备.h
#ifndef DEVICES_H
#define DEVICES_H
#include <QtCore>
#include <qdebug.h>
class DeviceController : public QObject
{
Q_OBJECT
public:
explicit DeviceController(QObject *parent = nullptr):QObject(parent){}
virtual ~DeviceController() {}
void doAllDevicesInit(){
emit deviceAInitSignal();
}
signals:
void deviceAInitSignal();
};
template<typename T> class BaseDevice {
public:
void init() {
static_cast<T*>(this)->doInit();
qDebug() << QString("BaseDevice initialized!");
}
};
class DeviceA : public BaseDevice<DeviceA> {
public:
void doInit() {
qDebug() << "DeviceA initialized!";
}
};
#endif // DEVICES_H
主文件
#include "devices.h"
int main(int argc, char *argv[])
{
Q_UNUSED(argc);Q_UNUSED(argv);
DeviceA deviceA;
DeviceController deviceController;
QObject::connect(&deviceController,&DeviceController::deviceAInitSignal,
&deviceA, &DeviceA::init);
deviceController.doAllDevicesInit();
return 0;
}
编译输出
Qt5.12.2/5.12.2/gcc_64/include/QtCore/qobjectdefs_impl.h:414:94:错误:从类型“QObject*”到类型“QtPrivate::FunctionPointer::*)()>::Object* 的无效静态转换' {aka 'BaseDevice*'} FuncType::template call(static_cast(this_)->function, static_cast(r), a);