如何在多个线程中将模板类型用作槽和信号参数

How to use template types as slot and signal parameters in multiple threads?

本文关键字:类型 参数 信号 线程      更新时间:2023-10-16

我可以以任何方式使用模板类型作为槽或信号参数吗?举个例子,我试图定义以下内容:

void exampleSignal(std::map<non_template_type_1,non_template_type_2> arg);
void exampleSlot(std::map<non_template_type_1,non_template_type_2> arg);

这会导致运行时出现以下情况:

QObject::connect: Cannot queue arguments of type 
    'std::map<non_template_type_1,non_template_type_2>'
(Make sure 'std::map<non_template_type_1,non_template_type_2>' 
    is registered using qRegisterMetaType().)

尝试向Q_DECLARE_METATYPE()注册std::map<non_template_type_1,non_template_type_2>会导致编译失败,显然不支持此操作。

作为一种变通方法,我使用QVariantMap而不是std::map。但我真的很想知道解决这个问题的正确方法;其中无法修改模板类。

编辑:我忘了提到信号和插槽是在不同的线程中发出和接收的。显然,运行时错误不会发生在单线程场景中。

这对我有效:

qRegisterMetaType< std::vector<float> >( "std::vector<float>" );
qRegisterMetaType< std::vector<int>   >( "std::vector<int>"   );
qRegisterMetaType< std::map<std::string,int64_t> >( "std::map<std::string,int64_t>" );

正如本线程中所解释的,您可以尝试使用typedef,包括QMetaType标头,然后同时使用Q_DECLARE_METATYPE宏和qRegisterMetaType函数(正如本线程在类似问题上所暗示的那样)。

如果您创建这样的类,并使用Qt-moc编译器自动创建QMetaObject,则没有问题:

class MyClass : public QObject
{
    Q_OBJECT
public:
    explicit MyClass(QObject *parent = 0)
        : QObject(parent)
    {
    }
public slots:
    void exampleSlot(std::map<non_template_type_1,non_template_type_2> arg);
signals:
    void exampleSignal(std::map<non_template_type_1,non_template_type_2> arg);
};

当然,您需要包括QObject以及std::map所在的任何位置。