Reputation: 1133
I don't know how to create a function pointer to a method in the Qt library that handles QVariant. I have a number of places in my code where I convert a QVariantList to a QList where SomeType can be QString, int, QMap or other variables that can be held in the QVariant object. At the time I'm going to use the method, the type is known.
Can I write a method using templates? Below is the pseudo code of the method I'd like to write
template <class T>
QList<T> QVariantListToQList(QVariantList qvList, (* QVariant::toXXX()) convert)
{
QList<T> qlistOfMembers;
foreach(T listMember, qvList)
{
qlist.OfMember.append(listMmeber.convert());
}
return qlistOfMembers;
}
A link to the documentation where this is discussed or a method using the correct syntax would be appreciated.
Upvotes: 1
Views: 977
Reputation: 206879
You don't need to do that. Use qvariant_cast
or the QVariant::value
functions, and drop that parameter altogether.
Something like:
template <class T>
QList<T> QVariantListToQList(QVariantList const& qvList)
{
QList<T> qlistOfMembers;
foreach(QVariant const& listMember, qvList)
{
qlistOfMembers.append(listMember.value<T>());
}
return qlistOfMembers;
}
If you want to do it your way, the syntax gets a bit tricky:
#include <QtCore>
template <class T>
QList<T> QVariantListToQList(QVariantList const& qvList,
T (QVariant::*convert)() const)
{
QList<T> qlistOfMembers;
foreach(QVariant const& listMember, qvList)
{
qlistOfMembers.append((listMember.*convert)());
}
return qlistOfMembers;
}
int main(void)
{
QVariantList vl;
vl.append(QVariant(QString("hello")));
qDebug() << vl;
QList<QString> sl = QVariantListToQList<QString>(vl, &QVariant::toString);
qDebug() << sl;
}
Upvotes: 3