Why const_cast doesn't work with raw template function with Eigen?

Viewed 99

A MWE:

#include <iostream>
#include <Eigen/Dense>
using namespace std;
using namespace Eigen;


void foo(const MatrixXf& m) {
  const_cast<MatrixXf& >(m).setZero();
}


template<typename T>
void bar(const Matrix<T, -1, -1>& m) {
  const_cast<Matrix<T, -1, -1>&>(m).setZero();
}


template<typename Derived>
void baz(const MatrixBase<Derived>& m) {
  const_cast<MatrixBase<Derived>& >(m).setZero();
}


int main() { 
  MatrixXf M = MatrixXf::Random(2, 6);
  cout << "Init:" << endl;
  cout << M << endl;

  foo(M.block(0, 0, 2, 2));
  cout << "After foo:" << endl;
  cout << M << endl;
  
  bar<float>(M.block(0, 2, 2, 2));
  cout << "After bar: " << endl; 
  cout << M << endl;

  baz(M.block(0, 4, 2, 2));
  cout << "After baz: " << endl; 
  cout << M << endl;
}

Output

Init:
  0.680375   0.566198   0.823295  -0.329554  -0.444451 -0.0452059
 -0.211234    0.59688  -0.604897   0.536459    0.10794   0.257742
After foo:
  0.680375   0.566198   0.823295  -0.329554  -0.444451 -0.0452059
 -0.211234    0.59688  -0.604897   0.536459    0.10794   0.257742
After bar: 
  0.680375   0.566198   0.823295  -0.329554  -0.444451 -0.0452059
 -0.211234    0.59688  -0.604897   0.536459    0.10794   0.257742
After baz: 
 0.680375  0.566198  0.823295 -0.329554         0         0
-0.211234   0.59688 -0.604897  0.536459         0         0

I read Eigen document Writing Functions Taking Eigen Types as Parameters. In the case we pass const reference to function, I was wondering why I cannot const_cast raw reference to achieve modifying data? In my example, why my foo and bar don't work? Is const_cast treat MatrixBase<Derived>& and Matrix<T, -1, -1>& diffierent?

0 Answers
Related