Is it possible to mix template-derived C++ classes with Qt's Q_OBJECT?

懵懂的女人 提交于 2019-11-29 02:00:15
Steve Townsend

You can't do this directly but there are usable work-rounds. See the article here.

While it is theoretically possible for moc to handle templates, it would be extremely complex to implement, and would be highly impractical to use: For each template instantiation, moc would have to generate the appropriate meta-object code, and the generated code would have to be included once per link unit---which becomes a nightmare to maintain once a template class is used with the same template parameter in different compilation units.

If the signals and slots don't require the template parameter to be part of the prototype, the workaround is to make a template class inherit a QObject subclass that provides the required signals and slots. If signals and slots need to use the template parameters, the Observer pattern is an alternative.

I just tried this code and it compiles and runs ok:

#include <QtCore/QCoreApplication>
#include <QObject>

class Word
{

};

template <typename T> class Dictionary
{

};

class WordDictionary : public Dictionary<Word>, QObject
{
    Q_OBJECT
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    WordDictionary wd();
    return a.exec();
}

May be I'm missing something?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!