c++qtcompiler-errors

error: C2664: 'QXmlStreamWriter::writeAttributes' : cannot convert parameter 1 from 'QVector<T>' to 'const QXmlStreamAttributes &'


I'm used to using the QStringList() << "a" << "b" idiom for quickly constructing a QStringList to pass to a function, but when I tried it with QXmlStreamAttributes, it didn't work.

This code compiles:

QXmlStreamAttributes attributes;
attributes << QXmlStreamAttribute("a", "b");
writer.writeAttributes(attributes);

But this one fails:

writer.writeAttributes(QXmlStreamAttributes() << QXmlStreamAttribute("a", "b"));

It fails with error:

C:\Workspace\untitled5\mainwindow.cpp:18: error: C2664: 'QXmlStreamWriter::writeAttributes' : cannot convert parameter 1 from 'QVector<T>' to 'const QXmlStreamAttributes &'
with
[
    T=QXmlStreamAttribute
]
Reason: cannot convert from 'QVector<T>' to 'const QXmlStreamAttributes'
with
[
    T=QXmlStreamAttribute
]
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

Another thing I noticed:

This code compiles:

QVector<QXmlStreamAttribute> v1 = (QVector<QXmlStreamAttribute>() << QXmlStreamAttribute("a", "b"));

But this one doesn't, even though QXmlStreamAttributes inherits from QVector<QXmlStreamAttribute>:

QXmlStreamAttributes v2 = (QXmlStreamAttributes() << QXmlStreamAttribute("a", "b"));

It fails with the same error.

Any idea why this happens?


Solution

  • QStringList has

    operator<<(const QString & str)
    

    but QVector has

    QVector<T> &    operator<<(const T & value)
    

    so your

    QVector<QXmlStreamAttribute> v1 = (QVector<QXmlStreamAttribute>() << QXmlStreamAttribute("a", "b"));
    

    compiles successfully.

    But your mistake is that QXmlStreamAttributes has no copy constructor, but you try use it, so you have 2 solutions:

    Use append:

    QXmlStreamAttributes v2;
    v2.append(QXmlStreamAttribute("a", "b"));
    qDebug()<< v2.first().name();
    

    Or use << in some different way:

    QXmlStreamAttributes v2;
    v2 << QXmlStreamAttribute("a", "b");
    qDebug()<< v2.first().name();
    

    Output is "a" in both cases.

    QXmlStreamAttributes QStringList QVector