如何在多个线程中将模板类型用作槽和信号参数
How to use template types as slot and signal parameters in multiple threads?
我可以以任何方式使用模板类型作为槽或信号参数吗?举个例子,我试图定义以下内容:
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
所在的任何位置。
相关文章:
- 在 c++ 中的模板实例化中使用带有构造函数的类作为类型参数
- 如何解决一元"*"(有"字符")错误的无效类型参数?
- "std::shared_ptr":不是参数"_Ty"的有效模板类型参数
- 具有可变参数非类型参数的模板专用化
- 函数类型参数的模板参数推导
- PowerShell 使用结构类型参数调用 C++ DLL 的导出函数
- 对于非常量指针类型的参数,未调用具有常量指针模板类型参数的功能
- 为模板传递非类型参数 agument
- 为什么带有类型参数的运算符 () 可以应用于 result_of 上下文中的类型?
- 使用其他模板类型参数作为要在函数签名中使用的类型别名声明
- 如何避免具有相同类型参数的函数中的错误
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- c++非类型参数包扩展
- 如何实现对参数顺序不可知的std::same_as的广义形式(即对于两个以上的类型参数)
- 在不同的模板参数包之间分发非类型参数包
- 如何在使用容器和字符串时强制使用显式分配器类型参数
- 错误:一元"*"的类型参数无效(具有"int"):使用 mergesort 计算
- EXPECT_CALL具有 unique_ptr 引用类型参数的模拟函数
- 作为模板类型参数,为什么 type[N] 与其专用版本不匹配----模板<类 T>类 S<T[]>
- C++ 模板:重载时找不到基类类型参数方法