Better_Software_Header_MobileBetter_Software_Header_Web

Find what you need - explore our website and developer resources

Qt, range-based for loops and structured bindings

Part 1

for (auto name: names) {
    // ...
}
{
    auto && __range = names;
    for (auto __begin = begin(names), __end = end(names); __begin != __end; ++__begin) {
        auto&& name = *__begin;
        // ...
    }
}
auto [x, y] = mousePosition();
auto [beginParticipant, endParticipant] = participants.equal_range("kdab");
for (auto [key, value]: stdMap) {
    // ...
}
for (auto value: map) {
    // ...
}
auto [key, value] = *map.keyValueBegin();
template <typename T>
class asKeyValueRange
{
public:
    asKeyValueRange(T &data)
        : m_data{data}
    {
    }
 
    auto begin() { return m_data.keyValueBegin(); }
 
    auto end() { return m_data.keyValueEnd(); }
 
private:
    T &m_data;
};
for (auto [key, value]: asKeyValueRange(map)) {
    // ...
}
{
    auto && __range = names;
    auto __begin = begin(names);
    auto __end = end(names);
    for ( ; __begin != __end; ++__begin) {
        auto&& name = *__begin;
        // ...
    }
}
auto __begin = begin(names), __end = end(names)
auto __begin = begin(names);
auto __end = end(names);
struct QSqlResultSentinel {};
 
QSqlResultSentinel end(QSqlQuery& query)
{
    return {};
}
class QSqlResultIterator {
public:
    QSqlResultIterator(QSqlQuery& query)
        : m_query(query)
    {
        m_query.next();
    }
 
    QSqlResultIterator& operator++()
    {
        m_query.next();
        return *this;
    }
 
    bool operator!=(QSqlResultSentinel sentinel) const
    {
        Q_UNUSED(sentinel);
        return m_query.isValid();
    }
 
    // ...
 
private:
    QSqlQuery& m_query;
};
 
QSqlResultIterator begin(QSqlQuery& query)
{
    return QSqlResultIterator(query);
}
class QSqlResultIterator {
public:
    // ...
 
    QSqlResultIterator& operator*()
    {
        return *this;
    }
 
    QVariant operator[] (int index) const
    {
        return m_query.value(index);
    }
 
    QVariant operator[] (const QString& name) const
    {
        return m_query.value(name);
    }
};
for (auto result: query) {
    qDebug() << result["name"] << result["surname"];
}

About KDAB


9 Comments

19 - Apr - 2020

Richi

20 - Apr - 2020

Ivan Čukić

19 - Apr - 2020

Pierre Clouthier

20 - Apr - 2020

Ivan Čukić

14 - Apr - 2022

Hamish M

14 - Apr - 2022

Ivan Čukić

12 - Oct - 2022

Adaita

14 - Oct - 2022

Ivan Čukić

19 - Oct - 2023

David Faure