KelvinS
KelvinS

Reputation: 3061

Is there a way to use QVariant with QVector?

Is there a way to use QVariant with QVector?

I would need to implement a function to compare two vectors, for example:

#include <QDebug>
#include <QVector>
#include <QString>

bool compareVectors(QVector<QVariant> vec1, QVector<QVariant> vec2)
{
    qDebug() << "Comparing vectors!";

    if( vec1 != vec2 )
    {
        qDebug() << "The vectors are different!";
        return false;
    }

    qDebug() << "The vectors are equal!";
    return true;
}

int main()
{
    QVector<double> v1;
    QVector<double> v2;
    v1 << 1 << 2;
    v2 << 3 << 4;

    QVector<QString> v3;
    QVector<QString> v4;
    v3 << "1" << "2";
    v4 << "3" << "4";

    compareVectors(v1, v1);
    compareVectors(v3, v4);

    return 0;
}

The two vectors passed by parameter will always have the same data type, for example:

compareVectors(QVector<int>, QVector<int>);
compareVectors(QVector<double>, QVector<double>);
compareVectors(QVector<QColor>, QVector<QColor>);
compareVectors(QVector<QString>, QVector<QString>);

When I try to run the above code I get the following error message:

error: no matching function for call to 'compareVectors'

Note: I'm using Qt 5.3.

Upvotes: 0

Views: 1554

Answers (1)

R Sahu
R Sahu

Reputation: 206567

You can't use a QVector<int> (or QVector<double>) when the argument type is QVector<QVariant>.

I would suggest making compareVectors a function template.

template <typename T>
bool compareVectors(QVector<T> vec1, QVector<T> vec2)
{
    qDebug() << "Comparing vectors!";

    if( vec1 != vec2 )
    {
        qDebug() << "The vectors are different!";
        return false;
    }

    qDebug() << "The vectors are equal!";
    return true;
}

Upvotes: 6

Related Questions