From 22ad2c3320acd4d20179d6c58e2727bdc0820582 Mon Sep 17 00:00:00 2001 From: Marc Mutz Date: Wed, 23 Nov 2022 15:51:48 +0100 Subject: [doc] QAnyStringView: document visit() For some reason, it wasn't documented. Pick-to: 6.4 6.2 Change-Id: I480623398dc33be91e82b24ac2616bcdd20da34b Reviewed-by: Paul Wicking --- src/corelib/text/qanystringview.qdoc | 66 ++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) (limited to 'src/corelib') diff --git a/src/corelib/text/qanystringview.qdoc b/src/corelib/text/qanystringview.qdoc index 9ab4c978ba..796202e2e1 100644 --- a/src/corelib/text/qanystringview.qdoc +++ b/src/corelib/text/qanystringview.qdoc @@ -339,6 +339,72 @@ \sa front(), {Sizes and Sub-Strings} */ +/*! \fn template decltype(auto) QAnyStringView::visit(Visitor &&v) const + + Calls \a v with either a QUtf8StringView, QLatin1String, or QStringView, depending + on the encoding of the string data this string-view references. + + This is how most functions taking QAnyStringView fork off into per-encoding + functions: + + \code + void processImpl(QLatin1String s) { ~~~ } + void processImpl(QUtf8StringView s) { ~~~ } + void processImpl(QStringView s) { ~~~ } + + void process(QAnyStringView s) + { + s.visit([](auto s) { processImpl(s); }); + } + \endcode + + Here, we're reusing the same name, \c s, for both the QAnyStringView + object, as well as the lambda's parameter. This is idiomatic code and helps + track the identity of the objects through visit() calls, for example in more + complex situations such as + + \code + bool equal(QAnyStringView lhs, QAnyStringView rhs) + { + // assuming operator==(QAnyStringView, QAnyStringView) didn't, yet, exist: + return lhs.visit([rhs](auto lhs) { + rhs.visit([lhs](auto rhs) { + return lhs == rhs; + }); + }); + } + \endcode + + visit() requires that all lambda instantiations have the same return type. + If they differ, you get a compile error, even if there is a common type. To + fix, you can use explicit return types on the lambda, or cast in the return + statements: + + \code + // wrong: + QAnyStringView firstHalf(QAnyStringView input) + { + return input.visit([](auto input) { // ERROR: lambdas return different types + return input.sliced(0, input.size() / 2); + }); + } + // correct: + QAnyStringView firstHalf(QAnyStringView input) + { + return input.visit([](auto input) -> QAnyStringView { // OK, explicit return type + return input.sliced(0, input.size() / 2); + }); + } + // also correct: + QAnyStringView firstHalf(QAnyStringView input) + { + return input.visit([](auto input) { + return QAnyStringView(input.sliced(0, input.size() / 2)); // OK, cast to common type + }); + } + \endcode +*/ + /*! \fn QAnyStringView::compare(QAnyStringView lhs, QAnyStringView rhs, Qt::CaseSensitivity cs) -- cgit v1.2.3