是否可以混合模板派生的C ++类与Qt的Q_OBJECT? [英] Is it possible to mix template-derived C++ classes with Qt's Q_OBJECT?

查看:1966
本文介绍了是否可以混合模板派生的C ++类与Qt的Q_OBJECT?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有以下类层次结构:

In my application, I have the following class hierarchy:

class Word
{
    ...
}

template <typename T> class Dictionary
{
    ...
};

class WordDictionary : public Dictionary<Word>
{
    Q_OBJECT

    ...
}

WordDictionary类解析需要很长时间的字典。我在一个单独的线程中运行解析函数,我希望它能够通知GUI线程不时地提供进度更新基于当前行号被解析。这就是为什么我想它是一个Q_OBJECT。我试图使基类Dictionary一个Q_OBJECT,但有一个消息,Q_OBJECT模板不支持。当我删除宏,只剩下WordDictionary作为Q_OBJECT,我得到一个一般形式的错误消息:

The WordDictionary class parses a dictionary which takes a long time. I am running the parsing function from within a separate thread and I want it to be able to signal the GUI thread from time to time to provide progress updates based on the current line number being parsed. That's why I want it to be a Q_OBJECT. I tried to make the base class Dictionary a Q_OBJECT but got a message that Q_OBJECT templates are not supported. When I removed the macro, leaving only WordDictionary as Q_OBJECT, I get a bunch of error messages of the general form:


.\GeneratedFiles \Release\moc_dictionary.cpp(44):错误C2039:'staticMetaObject':不是字典的成员

with

[

T = Word

]

.\GeneratedFiles\Release\moc_dictionary.cpp(44) : error C2039: 'staticMetaObject' : is not a member of 'Dictionary'
with
[
T=Word
]

有什么我可以做我的模板派生WordDictionary类一个Q_OBJECT

Is there anything I can do to make my template-derived WordDictionary class a Q_OBJECT other than hardcoding the template functions inside it, producing a lot of boilerplate code?

编辑:将模板声明更改为:

template <typename T> class Dictionary : public QObject

使代码编译。

推荐答案

你可以'直接这样做,但有可用的工作轮。请参阅此处的文章。

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


虽然理论上可以使用
moc来处理模板,但实现起来非常复杂,而
是非常不实用的:
对于每个模板实例化,moc
必须生成适当的
元对象代码,生成的
代码必须包含一次
每个链接单元---这成为一个
噩梦维护一个模板
类使用相同的模板
参数在不同的编译
单位。

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.

如果信号和槽不需要
模板参数作为
原型的一部分,解决方法是
使模板类继承
QObject子类,提供
所需的信号和插槽。如果
信号和槽需要使用
模板参数,则Observer
模式是另一种选择。

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.

这篇关于是否可以混合模板派生的C ++类与Qt的Q_OBJECT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆