Operator << for QString

Ilya Kobelevskiy picture Ilya Kobelevskiy · Apr 29, 2013 · Viewed 13.6k times · Source

It makes sense to implement << for QString like:

std::ostream&  operator <<(std::ostream &stream,const QString &str)
{
   stream << str.toAscii().constData(); //or: stream << str.toStdString(); //??
   return stream;
}

instead of writing

stream << str.toAscii().constData();

every time in the code.

However, since it is not in standard Qt library, I'm assuming there is any particular reason not to do so. What are the risks/inconvenience of overloading << as specified above?

Answer

fjardon picture fjardon · Apr 29, 2013

If the << operator is included in the Qt library every client of the library will have to use the exact same implementation. But due to the nature of QString it is far from obvious this is what these clients want. Some people writing software interacting with legacy file in western europe may want to use Latin1() characters, US people may go with Ascii() and more modern software may want to use Utf8().

Having a single implementation in the library would restrict unacceptably what can be done with the whole library.