1.4 KiB
title | date | draft | tags | series | ||
---|---|---|---|---|---|---|
Obscure Qt: Qt5 QMap and C++20 Ranges | 2024-10-30 | false |
|
|
I was working on a project that still uses Qt5 and I wanted to port from Qt's own foreach
keyword. In Qt6 it's possible to write code like this:
QMap<QString, int> map;
...
for (int value : std::as_const(map))
cout << value << endl;
Unfortunately in Qt5 this is not possible, as it was never implemented. You don't even have asKeyValueRange()
!
You may have seen it before, but someone has already written a great StackOverflow answer backporting this feature to Qt5. However, this codebase has C++20 available! (Yes, really.) The SO answer needs to add a whole bunch of extra wrapper code, but it's actually possible to use C++ for
by using std::ranges::subrange
:
QMap<QString, int> map;
...
for (int value : std::ranges::subrange(map.constBegin(), map.constEnd()))
cout << value << endl;
Take care when porting to ensure the previous foreach
code didn't depend on a copy of the container. Use constBegin()
/constEnd()
when needed to ensure the container doesn't detach.