I am using Eigen library and its block operations, according to https://eigen.tuxfamily.org/dox/group__TutorialBlockOperations.html the blocks are both lvalues and rvalues. But the following program does not compile:
#include "Eigen/Dense"
#include <iostream>
int main() {
Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> m(4, 4);
m << 1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
13, 14, 15, 16;
Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> &column = m.col(0);
}
In this program, I want to use column as a reference to the matrix m so I could alter the elements in-place. The error message is:
test_eigen_rvalue.cc: In function ‘int main()’:
test_eigen_rvalue.cc:11:73: error: invalid initialization of non-const reference of type ‘Eigen::Matrix<float, -1, -1>&’ from an rvalue of type ‘Eigen::DenseBase<Eigen::Matrix<float, -1, -1> >::ColXpr {aka Eigen::Block<Eigen::Matrix<float, -1, -1>, -1, 1, true>}’
Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> &column = m.col(0);
It seems the issue is that m.col(0) is not an lvalue.
The block
method does not return a Matrix
object but a Block<>
expression. In this case, it is a good idea to use the auto
keyword (but be careful):
auto column = m.col(0);
Or use the convenient typedefs:
MatrixXf::ColXpr column = m.col(0);
Or even a Ref<>
:
Ref<VectorXf> column = m.col(0);
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