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?
I don't think there is any particular reason for excluding (nor including) this in the
Qt library
. Only problem that could possibly appear here is a possibility thatstd::ostream
object could modify the contents of the parameter passed tostd::ostream::operator<<
function.However, in the reference it is clearly stated that this function will modify the parameter if string buffer is passed - there is nothing about the other types, so I guess (and the common-sense is telling me) that operator<< will not modify
char*
parameter. Also, on this page there is nothing about modifying the passed object.Last thing: instead of using
QString::toAscii().constData()
, you could useQString::toStdString()
orqPrintable(const QString&)
macro.The accepted answer points out some valid reasons for why there is no
operator<<
function forQString
.One can easily overcome those reasons by providing some convenience functions and maintaining some state in an application specific
namespace
.Output:
It's not necessary to implement such thing, as long as there exists a convenient solution like this one, involving QTextStream
QTextStream is quite powerfull...
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.