I have trouble to implement following code
template <class T>
struct Foo
{
std::vector<T> vec;
std::vector<T> getVector() && {
// fill vector if empty
// and some other work
return std::move(vec);
}
std::vector<T> getVectorAndMore() &&
{
// do some more work
//return getVector(); // not compile
return std::move(*this).getVector(); // seems wrong to me
}
};
int main()
{
Foo<int> foo;
auto vec = std::move(foo).getVectorAndMore();
}
The problem is that I can't call getVector
inside getVectorAndMore
because this
is not rvalue. To make the code compile, I had to cast this
to rvalue.
Is any good way to implement such code?
with return getVector();
error message is
main.cpp:17:16: error: cannot initialize object parameter of type 'Foo<int>' with an expression of type 'Foo<int>'
return getVector(); // not compile
^~~~~~~~~
main.cpp:26:31: note: in instantiation of member function 'Foo<int>::getVectorAndMore' requested here
auto vec = std::move(foo).getVectorAndMore();
^
1 error generated.
Coliru
return getVector(); // not compile
This is equivalent to this:
return this->getVector(); // not compile
which wouldn't compile, because this
is an lvalue, not an rvalue and getVector()
can be invoked only on rvalue, hence the error.
Note that this
is always an lvalue — even inside rvalue-ref member function!
return std::move(*this).getVector();
That is the correct way to invoke getVector()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With