0

我正在尝试使用带有 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);

4

1 回答 1

1

感谢 drescherjm 评论,解决方法如下

设备.h

...

template<typename T> 
class BaseDevice: public QObject  {
//Q_OBJECT, Error: Template classes not supported by Q_OBJECT
public:
    explicit BaseDevice(QObject *parent = nullptr):QObject(parent){}
    virtual ~BaseDevice() {}
    void init() {
        static_cast<T*>(this)->doInit();
        qDebug() << QString("BaseDevice initialized!");
    }
};

class DeviceA : public BaseDevice<DeviceA> {
Q_OBJECT
public:
    explicit DeviceA(QObject *parent = nullptr):BaseDevice<DeviceA>(parent){}
    virtual ~DeviceA() {}
    void doInit() {
        qDebug() << "DeviceA initialized!";
     }
};
#endif // DEVICES_H
于 2019-05-24T12:30:45.137 回答