c++ - 是否可以将模板派生的 C++ 类与 Qt 的 Q_OBJECT 混合使用?

标签 c++ qt templates qobject

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

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 时,我收到一堆一般形式的错误消息:

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

除了在其中硬编码模板函数,生成大量样板代码之外,我还能做些什么来使我的模板派生的 WordDictionary 类成为 Q_OBJECT?

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

template <typename T> class Dictionary : public QObject

编译代码。不过,我不确定我是不是在做一些愚蠢的事情,也不确定这是否会正常工作。

最佳答案

您不能直接执行此操作,但有可用的变通方法。见文章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.

关于c++ - 是否可以将模板派生的 C++ 类与 Qt 的 Q_OBJECT 混合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4238204/

相关文章:

c++ - 如何编写 C 或 C++ 程序来充当内存和 CPU 周期填充器?

c++ - 在函数定义中指定参数默认值导致错误 C2143 : syntax error : missing ')' before '='

C++修改对象指针指向但不保留值

c++ - 如何在选择不同类型的容器之间做出决定?

java - 如何熟练高效地使用 NetBeans?

没有 typedef 的模板类的 C++ 模板,这可能吗?

c++ - 大型跨平台软件项目的技巧/资源

c++ - QT 不清楚的移位运算符行为

qt - 是否有任何特定于 Qt 的分析器?

c++ - 使用衰减与完美转发