Stack Overflow Asked by Hen3 on November 4, 2021
I have recently learned about r-value references. In order to more thoroughly experiment I decided to write a simple DenseMatrix class. My question is is it possible to write any function ( Transpose for this example ) such that for auto A = B.Transpose()
separate matrix is returned, but for auto A = (B + C).Transpose()
the result of the Transpose is calculated in place?
Yes, you can overload the Transpose
member function on the ref-qualification of the object it's being called on:
class DenseMatrix {
DenseMatrix Transpose() const & { // #1 called on l-values
auto copy = *this;
// transpose copy
return copy;
}
DenseMatrix&& Transpose() && { // #2 called on r-values
// transpose *this
return std::move(*this);
}
};
So you get the result:
B.Transpose(); // calls #1
(B + C).Transpose(); // calls #2
Here's a demo.
Note that you could implement the l-value overload in terms of the r-value overload, like this:
DenseMatrix Transpose() const & {
auto copy = *this;
return std::move(copy).Transpose();
}
Here's a demo.
Answered by cigien on November 4, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP