In Qt5, this
#include <QString>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> v{0, 1, 1, 2, 3, 5, 8};
QString qs("target");
// Search the vector for the string
std::find(v.begin(), v.end(), qs);
}
will build (compile and link). There are very few circumstances where you mean what it will actually do (in this case it's a very expensive no-op), but it is valid code.
This works because of a chain of "helpful" features:
- You can construct a QChar from an int:
QChar(int rc) noexcept
.
- There is a equality test between QChar and QString:
bool operator==(QChar lhs, const QString &rhs) noexcept
.
- The find template uses
operator==
between the contents of the vector and the target.
Each of the behaviors is desireable in isolation, so we don't want to remove any of these options entirely. What causes the surprise is the implicit nature of the type conversion.1 Core guidelines C46 and C164 discuss the uses of explicit
annotation to prevent this kind of thing.
BTW: the above code will not compile in QT6 which is a small but significant improvement.
1 Shout out to all the strong typing fans out there.