#include <vector>
class MyContainer {
public:
std::vector<int> data;
// begin() only defined for rvalues
auto begin() && { return data.begin(); }
auto end() && { return data.end(); }
};
MyContainer container;
container.data = {1, 2, 3};
// why not working ? compile error;
for (int x : MyContainer(container)) {
std::cout << x << " ";
}
clang c++ 20 complain:
'this' argument to member function 'begin' is an lvalue, but function has rvalue ref-qualifier;
but why ? MyContainer(container) is rvalue, it SHOULD match begin() &&, right ?
I know using MyContainer(container).begin() is ok, but how to use it in for range loop directly?
update: why i want those to work ?
for iter = xxx.begin(); if xxx is rvalue, *iter return rvalue too; so, for
for (auto &&e : Container()) {
x = e; // call move directly;
}
for (auto &&e : container) {
x = e; // call copy directly;
}
it's very convenient for implements many move aware of algorithm; but seems standard not aware of it for now;
hops it update in future!
solution for current c++ standard (20)
for (auto itb = move(container).begin(), ite = move(container).end(); itb != ite; ++ itb) {
x = *itb; // ok, call move;
}
for (auto &&e : container) {
x = e; // ok, call copy as it is;
}