emplate classes not supported by Q_OBJECT
时间: 2024-05-07 16:15:58 浏览: 121
meta::Expr{T_emplate}-开源
As a language feature, template classes cannot inherit QObject, so they cannot use the Q_OBJECT macro. This is because the MOC (Meta-Object Compiler) cannot generate meta-object code for template classes at compile-time.
However, it is still possible to use templates in Qt. One approach is to create a non-template base class that inherits QObject and contains the Q_OBJECT macro. Then, derive the template class from the base class.
For example:
```
class MyBase : public QObject {
Q_OBJECT
public:
MyBase(QObject *parent = nullptr) : QObject(parent) {}
};
template<typename T>
class MyTemplate : public MyBase {
public:
MyTemplate(QObject *parent = nullptr) : MyBase(parent) {}
};
```
This way, any template class that derives from MyBase can use signals and slots, as well as other features provided by QObject.
Another approach is to use the Q_DECLARE_METATYPE macro to register the template class as a meta-type. This allows the template class to be used in signals and slots, but it does not provide the full functionality of QObject.
```
template<typename T>
class MyTemplate {
public:
// ...
};
Q_DECLARE_METATYPE(MyTemplate<int>);
```
In summary, while template classes cannot use the Q_OBJECT macro directly, there are workarounds to enable them to use signals and slots in the Qt framework.
阅读全文