8

I need to define a function that takes a const C array and maps it into an Eigen map. The following code gives me an error:

double data[10] = {0.0};
typedef Eigen::Map<Eigen::VectorXd> MapVec;

MapVec fun(const double* data) {
  MapVec vec(data, n);
  return vec;
}

If I remove const from the function definition the code works fine. But is it possible to retain the const without any errors?

Thanks.

user3294195
  • 1,748
  • 1
  • 19
  • 36

1 Answers1

12

If the Map's parameter is a non-const type (e.Eigen::VectorXd) then it assumes that it can modify the raw buffer (in your case *data). As the function expects a const qualified buffer, you have to tell the map that it's const. Define your typedef as

typedef Eigen::Map<const Eigen::VectorXd> MapVec;

and it should work.

Avi Ginsburg
  • 10,323
  • 3
  • 29
  • 56
  • does it mean that the MapVec is a const and cannot be changed later? – X.Arthur Mar 26 '18 at 09:26
  • 2
    @X.Arthur The original data cannot be changed as it's `const`, as in OP. The address of the data to which the Map points cannot be changed either, except with placement new, although that has nothing to do with OP. – Avi Ginsburg Mar 26 '18 at 09:29