[Development] qMoveToConst helper for rvalue references to movable Qt containers?
Elvis Stansvik
elvstone at gmail.com
Sat Oct 20 14:43:45 CEST 2018
Hi all (first post),
In Qt 5.7+ there's qAsConst, an std::as_const implementation for those
who are not on C++17 yet, which is convenient for iterating over Qt
containers using range-based for loops without causing a detach.
For good reasons there's no version of qAsConst that takes an rvalue
reference, so you can't do e.g. for (auto foo :
qAsConst(returnsQtContainer()) { ... }. Instead you must do const
auto stuff = returnsQtContainer(); for (auto foo : stuff) { ... }.
In our application we added a helper like
template <typename T>
const T moveToConst(T &&t)
{
return std::move(t);
}
that we use for these cases. It just moves the argument to a const
value and returns it. With that we can do for (auto foo :
moveToConst(returnsQtContainer()) { ... }.
Since it's such a common pattern to want to iterate a returned Qt
container, what would you think of having such a helper
(qMoveToConst?) in Qt?
Cheers,
Elvis
More information about the Development
mailing list