c ++函数指针,用于将QVariant转换为{自定义类型 [英] c++ function pointer used to convert a QVariant to {a custom type
问题描述
QVariant包含要转换为自定义类型MyClass或MyClass2的QMap对象。
A QVariant is holding a QMap object that is to be converted into a custom type, MyClass or MyClass2.
示例:
class MyClass{
int item1;
int item2;
QString string1;
AnotherClass subclass;
};
class MyClass2{
int item1;
QString string1;
AnotherClass subclass;
};
函数已被写入以将QVariant转换为关联类
functions have been written to convert the QVariant to the associated classes
MyClass QVariantToMyClass1(QVariant);
MyClass2 QVariantToMyClass1(QVariant);
我的问题是,在模板函数中,传递函数指针的正确方法是什么?下面显示的代码返回一个错误'const class QVariant没有成员名为convFunct'
My question is, in a template function what is the proper way to pass in the function pointer? The code shown below returns an error 'const class QVariant has no member named convFunct'
template<class T>
QList<T> QVariantToQList(QVariant & qv,T (* convFunct)() )
{
// Create the list that will hold the return values
QList<T> qListOfMembers;
if(qv.typeName() == "QVariantMap"){
foreach(QVariant const& mapMember,qv.toMap())
{
qListOfMembers.append(mapMember.convFunct());
}
}
else if (qv.typeName() == "QVariantList"){
foreach(QVariant const& listMember,qv.toList())
{
qListOfMembers.append(listMember.convFunct());
}
}
else
{
qDebug()<< "QVariantToQList currently is implemented only for QMap and QList types";
throw ;
}
return qListOfMembers;
}
这是一个后续问题到以前的问题这个问题和这一个的区别是T是'MyClass'或'MyClass2'而不是
This is a follow-up question to a previous question The difference between that question and this one is the T is 'MyClass' or 'MyClass2' instead of a type that is normally held by a QVariant.
推荐答案
如果我正确理解您的问题, convFunct
应该是一个获得 QVariant
并返回 MyClass
或 MyClass2
,是否正确?如果你的答案是肯定的,那么这个函数应该得到一个类型 QVariant
的参数,你的函数没有参数,所以结果是:
If I understand your question correctly, convFunct
supposed to be a function that get a QVariant
and return an instance of MyClass
or MyClass2
, is it correct? if your answer is yes, then this function should get a parameter of type QVariant
and your function get no parameter, so the result is:
template<class T>
QList<T> QVariantToQList(QVariant & qv,T (*convFunct)(QVariant const&) )
{
// Create the list that will hold the return values
QList<T> qListOfMembers;
if(qv.typeName() == "QVariantMap"){
foreach(QVariant const& mapMember,qv.toMap())
{
qListOfMembers.append(convFunct(mapMember));
}
}
else if (qv.typeName() == "QVariantList"){
foreach(QVariant const& listMember,qv.toList())
{
qListOfMembers.append(convFunct(listMember));
}
}
else
{
qDebug()<< "QVariantToQList currently is implemented only for QMap and QList types";
throw ;
}
return qListOfMembers;
}
这篇关于c ++函数指针,用于将QVariant转换为{自定义类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!