Eigen矩阵库的模板类型转换

时间:2015-08-14 07:14:23

标签: c++ eigen

我正在尝试使用Eigen库输入模板化的矩阵。

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

它不起作用。 有人可以帮助我正确的syntex。

1 个答案:

答案 0 :(得分:3)

您的功能签名不完整,但我想您遗漏的主要内容是使用template keyword for the function call

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

一个完整的工作示例:

#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;
}

在编译和运行时,打印

3 0 0
0 6 0
0 0 9

到标准输出。