2

I'm working with Eigen library and trying to understand what authors wanted to say about resizing base class within template.

#include <iostream>
#include <Eigen/Dense>

using namespace std;
using namespace Eigen;

template <typename Derived, typename OtherDerived>
void cov(const MatrixBase<Derived>& x, const MatrixBase<Derived>& y, MatrixBase<OtherDerived> const & C_)
{
  typedef typename Derived::Scalar Scalar;
  typedef typename internal::plain_row_type<Derived>::type RowVectorType;
 
  const Scalar num_observations = static_cast<Scalar>(x.rows());
 
  const RowVectorType x_mean = x.colwise().sum() / num_observations;
  const RowVectorType y_mean = y.colwise().sum() / num_observations;
 
  MatrixBase<OtherDerived>& C = const_cast< MatrixBase<OtherDerived>& >(C_);
  
  C.derived().resize(x.cols(),x.cols()); // resize the derived object
  C = (x.rowwise() - x_mean).transpose() * (y.rowwise() - y_mean) / num_observations;
}

int main()
{
  MatrixXf x = MatrixXf::Random(100,3);
  MatrixXf y = MatrixXf::Random(100,3);
  MatrixXf C;
  cov(x, y, C);
  cout << C << endl;
    
  return 0;
}

As I understand the goal is to resize the base class and to do that they use MatrixBase<OtherDerived> const & C_ which is then const-casted const_cast<> to a derived class and they resize this derived class...

I wondered what would be if instead MatrixBase<OtherDerived> const & C_ I simply write MatrixBase<OtherDerived>& C and comment the const_cast<> line? Apparently the example still works and you can check that using online compiler

So why authors have dedicated a chapter for that task if there is a simpler solution? Probably I'm missing something?

Kerim
  • 171
  • 3
  • 10
  • 1
    That must be a mistake. It is very bad design to hide the intention of a function by its signature. To const_cast internally makes no sense in terms of reasonable design... – Ralf Ulrich Sep 26 '21 at 07:46

0 Answers0