P. Preet
P. Preet

Reputation: 15

Template type casting of Eigen Matrix library

I am trying to type cast a templated matrix using Eigen library.

function( const Eigen::MatrixBase < Derived1 > &mat1,
                Eigen::MatrixBase < Derived2 > &mat2 )
{
    mat2 = coefficient * mat1.derived().cast < Derived2::Scalar >();
}

it is not working. can someone help me with correct syntex.

Upvotes: 0

Views: 1889

Answers (1)

vindvaki
vindvaki

Reputation: 534

Your function signature is incomplete, but I guess that the main thing you are missing is to use the template keyword for the function call as such:

mat2 = coefficient * mat1.template cast <typename Derived2::Scalar> ();

A full working example:

#include <eigen3/Eigen/Core>
#include <iostream>

template<typename Derived1, typename Derived2>
void mul(const typename Derived1::Scalar& coefficient,
         const Eigen::MatrixBase<Derived1>& mat1,
         Eigen::MatrixBase<Derived2>& mat2)
{
  mat2 = coefficient * mat1.template cast <typename Derived2::Scalar> ();
}

int main() {

  Eigen::Matrix3f a;
  a << 1.0, 0.0, 0.0,
       0.0, 2.0, 0.0,
       0.0, 0.0, 3.0;

  Eigen::Matrix3i b;
  b << 1, 0, 0,
       0, 1, 0,
       0, 0, 1;

  mul(3.5, a, b);

  std::cout << b << "\n";

  return 0;
}

Which, when compiled and run, prints

3 0 0
0 6 0
0 0 9

to the standard output.

Upvotes: 4

Related Questions