Search code examples
c++qtcompiler-errorsoperator-overloading

error: no match for 'operator<<' (operand types are 'QTextStream' and 'const char [3]')


This is a piece of Qt-based code that is a year old and that I probably have compiled in all sorts of contexts and many, many times, and every time unbeknownst to me. It is in a file called DPolygon.cpp where it seems we are defining DPolygons (no idea what this is even) :

QTextStream& operator<<(QTextStream& stream, const DPolygon& polygon)
{
    std::for_each(polygon.constBegin(), polygon.constEnd(),
                  [&stream](const QPointF& pnt) { stream << "( "<< pnt.x() << ", " << pnt.y() << " ) "; } );

    return stream;
}

Today I (newly) get this error :

error: no match for 'operator<<' (operand types are 'QTextStream' and 'const char [3]')
  236 |                   [&stream](const QPointF& pnt) { stream << "( "<< pnt.x() << ", " << pnt.y() << " ) "; } );
      |                                                   ~~~~~~ ^~ ~~~~
      |                                                   |         |
      |                                                   |         const char [3]
      |                                                   QTextStream

In qtextstream.h in the declaration of QTextStream I can see :

     QTextStream &operator<<(const char *c);

I know arrays and pointers aren't exactly the same thing, but this was working until today ! What could have changed or happened ? What other info could I give that would help ?

This actually first appeared when I clicked "rebuild".

We are using Qt 5.12.11 and Qt Creator 12.0.1 and CMake at least 3.19 and MinGW 7.3.0. None of this has changed recently in a way that would meaningfully be related.


Solution

  • QTextStream has an operator<<(const char*) which should be getting called here.

    this was working until today !

    The most likely cause is that the file where your operator<< is defined doesn't #include <QTextStream> on its own, but relies on getting it from somewhere else. This is sometimes called "leaky headers" and may lead to code being broken by a Qt update, or by other seemingly unrelated includes being changed.

    QTextStream is likely still forward-declared somewhere, but operator<< needs the include. You should always include what you use to prevent these issues, and tools such as include-what-you-use can help with that.