[Interest] Template-derived classes using MOC

Thiago Macieira thiago.macieira at intel.com
Sat Sep 5 09:38:50 CEST 2015


On Saturday 05 September 2015 07:31:47 Curtis Mitch wrote:
> Is the following code a valid use of MOC? If not, why? I couldn't see
> anything mentioned in the old Qt Quarterly article [1] about this specific
> usage.

Hi MItch

It will compile, because:

> #include <QtCore>
> 
> class AbstractBase : public QObject
> {
> public:
>     AbstractBase() {}
> 
>     virtual void virt() = 0;
> };

This is a normal class. You didn't have Q_OBJECT here, but you could have it 
and it should be fine.

> template<typename T>
> class Base : public AbstractBase
> {
> public:
>     Base() {}
> 
>     virtual void virt() {}
> 
> private:
>     QVector<T> mContainer;
> };

Moc is not involved in this class. You cannot add Q_OBJECT to this one.

> class Derived : public Base<QString>
> {
>     Q_OBJECT
>     Q_PROPERTY(int blah READ blah WRITE setBlah)
> 
> public:
>     Derived() : mBlah(0) {}
>     ~Derived() {}
> 
>     int blah() const { return mBlah; }
>     void setBlah(int blah) { mBlah = blah; }
> 
> public slots:
>     void foo() { qDebug() << Q_FUNC_INFO; }
> 
> signals:
>     void sig();
> 
> private:
>     int mBlah;
> };

This one is a bit weird, bit will also compile. The moc-generated code will 
look for Base<QString>'s meta object, which it *does* have, since it inherited 
from AbstractBase. It's just not a meta object specific to the template class.

-- 
Thiago Macieira - thiago.macieira (AT) intel.com
  Software Architect - Intel Open Source Technology Center




More information about the Interest mailing list