简体   繁体   中英

c++ function pointer used to convert a QVariant to {a custom type

A QVariant is holding a QMap object that is to be converted into a custom type, MyClass or MyClass2.

Example:

class MyClass{
   int item1;
   int item2;
   QString string1;
   AnotherClass subclass;
};

class MyClass2{
   int item1;
   QString string1;
   AnotherClass subclass;
};

functions have been written to convert the QVariant to the associated classes

MyClass QVariantToMyClass1(QVariant);
MyClass2 QVariantToMyClass1(QVariant);

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;
}

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM