模板类型铸造的特征矩阵库

Template type casting of Eigen Matrix library

本文关键字:特征 类型      更新时间:2023-10-16

我正在尝试使用Eigen库类型转换模板矩阵。

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

它不工作。谁能帮我纠正一下语法?

您的函数签名不完整,但我猜您缺少的主要内容是使用模板关键字进行函数调用:

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