gpt4 book ai didi

c++ - "Static polymorphism with Qt signal/slot: What is wrong?"

转载 作者:行者123 更新时间:2023-11-28 04:17:29 25 4
gpt4 key购买 nike

我试图在 Qt 信号/槽机制中使用静态多态而不是动态多态。但是我得到编译错误。我的代码有什么问题?什么是解决方法?

devices.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

main.cpp

#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: error: invalid static_cast from type ‘QObject*’ to type ‘QtPrivate::FunctionPointer::*)()>::Object*’ {aka ‘BaseDevice*’} FuncType::template call(static_cast(this_)->function, static_cast(r), a);

最佳答案

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

devices.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

关于c++ - "Static polymorphism with Qt signal/slot: What is wrong?",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56292004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com