Comparing QStringView with std::string and char*
-
wrote on 25 Feb 2022, 21:16 last edited by AlQuemist
QStringView
is introduced as a light-weight reference toQString
, similar to the relation ofstd::string_view
tostd::string
in C++.
Yet it apparently lacks some important functionality: Comparison tochar*
orstd::string
with the==
operator.
One has always to convert either the lhs or rhs of the comparison toQString
which entails a full copy and hence, violates the raison d’être ofQStringView
.
See also https://stackoverflow.com/q/18228720.Is there a better way for such comparisons (in Qt5 or Qt6)?
- Minimal example
#include <string> #include <iostream> #include <QString> #include <QStringView> int main() { constexpr const char* const str0 {"my string"}; QStringView qstrv0(QString::fromStdString(str0)); if(qstrv0 == QString::fromStdString(str0)) std::cout << "1) equal" << std::endl; if(qstrv0.toString() == str0) std::cout << "2) equal" << std::endl; std::string str1 = "my string"; QStringView qstrv1(QString::fromStdString(str1)); if(qstrv1 == QString::fromStdString(str1)) std::cout << "3) equal" << std::endl; if(qstrv1.toString() == str1) // does not compile std::cout << "4) equal" << std::endl; if(qstrv0 == str0) // does not compile std::cout << "5) equal" << std::endl; if(qstrv0 == str1) // does not compile std::cout << "6) equal" << std::endl; return 0; }
- Compile & link:
$ qmake -project $ qmake $ make
-
@AlQuemist said in Comparomg QStringView with std::string and char*:
Comparison to char* or std::string with the == operator.
How should this work - char* and std::string are just a bunch of bytes without any encoding. QString on the other side is well encoded utf-16.
-
@AlQuemist said in Comparomg QStringView with std::string and char*:
Comparison to char* or std::string with the == operator.
How should this work - char* and std::string are just a bunch of bytes without any encoding. QString on the other side is well encoded utf-16.
wrote on 6 Dec 2024, 09:30 last edited by@Christian-Ehrlicher Sometimes you need to compare a QStringView with string literals. In the following example, when parsing a xml file, I need to differentiate tags by their name. Since QXmlStreamReader.name() returns a QStringView, compares it to a const char * literal is very natural. Wrap all comparable literals using QLatin1String is very inconvinient.
QXmlStreamReader xml; xml.setDevice(&file); while(!xml.atEnd()) { xml.readNext(); switch (xml.tokenType()) { case QXmlStreamReader::TokenType::StartElement: if (xml.name() == "item") { ... } ... } }
-
And what the big difference to
if (xml.name() == "item"_L1) {
Are we really discussing here about three characters?