c++ - 通过模板发布 C++ Eigen::Matrix 类型

标签 c++ templates eigen eigen3

我正在编写一个根据类型(floatdouble )模板化并使用 Eigen::Matrix 的 C++ 函数在内部。该函数将使用 float 的组合, double , 和模板化类型 Eigen:Matrix对象。 Eigen::Matrix<>::cast()适用于 doublefloat ,尽管我在将它与模板化类型一起使用时遇到了一个奇怪的问题。见下面的代码:

#include "Eigen/Core"  // Version 3.2.4 (eigen-eigen-10219c95fe65)

template <typename Scalar>
void Foo() {
  Eigen::Matrix<double, 3, 1> mat_d = Eigen::Matrix<double, 3, 1>::Zero();
  Eigen::Matrix<float,  3, 1> mat_f = Eigen::Matrix<float,  3, 1>::Zero();
  Eigen::Matrix<Scalar, 3, 1> mat_s = Eigen::Matrix<Scalar, 3, 1>::Zero();

  mat_d = mat_f.cast<double>();  // Works
  mat_f = mat_f.cast<float>();   // Works

  mat_s = mat_f.cast<Scalar>();  // Works
  mat_s = mat_d.cast<Scalar>();  // Works

  mat_d = mat_s.cast<double>();  // Broken
  mat_f = mat_s.cast<float>();   // Broken
}

int main() {
  Foo<double>();
  Foo<float>();
}

编译结果如下:

> g++ casting.cpp
casting.cpp: In function ‘void Foo()’:
casting.cpp:16:22: error: expected primary-expression before ‘double’
   mat_d = mat_s.cast<double>();  // Broken
                      ^
casting.cpp:16:22: error: expected ‘;’ before ‘double’
casting.cpp:17:22: error: expected primary-expression before ‘float’
   mat_f = mat_s.cast<float>();   // Broken
                      ^
casting.cpp:17:22: error: expected ‘;’ before ‘float’

因为我只用 Scalar 实例化模板作为doublefloat ,我想 Scalar函数调用应具有与硬编码相同的效果 float/double类型。

一些更多的系统信息:

预先感谢您的帮助!

最佳答案

谢谢,@piotr-s!看起来这不是特定于 Eigen 的东西,但更普遍的是一些用于调用模板化成员函数的棘手语法。

这是一个相关问题:How to call a template member function?

答案如下:

mat_d = mat_s.template cast<double>();

关于c++ - 通过模板发布 C++ Eigen::Matrix 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29754251/

相关文章:

c++ - 如何将 Eigen::eigenvector().col(0).real() 转换为 std vector ?

c++ - 使用 Eigen 类对 vector 中的某些数字求和

c++ - 为在 C++ 应用程序中作为函数参数传递的文件运行 'iconv' 命令

c++ - 在没有提供模板的情况下调用模板函数?

c++ - std::set 和 boost::shared_ptr 唯一键识别问题

c++ - 析构函数的模板特化

c++ - 派生类型名

c++ - Eigen::vector::normalize 精度

c++ - 在 C++ 命名空间中包含旧库

c++ - 在具有虚拟析构函数的基类的子类中不指定析构函数是否安全?