I have an Eigen (3.4.0) related question that really troubles me. In this C++ code, there's a function pass_by_nonconst_ref
which takes a non-const reference to a eigen matrix, and that does some work on the matrix.
#include <iostream>
#include "Eigen/Eigen"
using namespace std;
// A function that takes a non const reference to a vector
void pass_by_nonconst_ref(Eigen::Matrix<float, -1, 1>& vec) {
// do some work on your matrix...
vec(0) = 1;
}
int main() {
// This works without any problem.
Eigen::Matrix<float, -1, 1> x1(3);
x1 << 0.0, 0.0, 0.0 ;
pass_by_nonconst_ref(x1);
cout << "x = " << x1 << endl ;
// But this does not !!!!
Eigen::Matrix<float, 3, 1> x2;
x2 << 0.0, 0.0, 0.0 ;
// if you uncomment this line, it won't compile...
// pass_by_nonconst_ref(x2);
cout << "x = " << x2 << endl ;
// And to check that x2 is not a temporary?
Eigen::Matrix<float, 3, 1> x3;
x3 << 0.0, 0.0, 0.0 ;
x3(0) = 1;
cout << "x = " << x3 << endl ;// this works
return 0;
}
This code only compiles if I pass to the function an object the type Eigen::Matrix<float, -1, 1>
. If I use instead Eigen::Matrix<float, 3, 1>
, then there is the following compilation error:
error: cannot bind non-const lvalue reference of type ‘Eigen::Matrix<float, -1, 1>&’ to an rvalue of type ‘Eigen::Matrix<float, -1, 1>’
22 | pass_by_nonconst_ref(x2);
The only difference (that I see) is that x2
knows it only has 3 rows, whereas x1
has a dynamic number of rows. I am aware that a non-const reference can't bind to a temporary, but I really don't see why x2
can be considered as one and not x1
.
I can't understand why I have to specify the dynamic type to make it work. It got me quite curious. Is there something obvious that I am missing ? I suspect it is related to type conversion.
Eigen::Matrix<float, -1, 1>
andEigen::Matrix<float, 3, 1>
are two different types and your function expects aEigen::Matrix<float, -1, 1>
. You will get the same error if your function parameter was of typeint&
and you were passing it adouble
. – Amphibolous