Issue casting C++ Eigen::Matrix types via templates

怎甘沉沦 提交于 2019-12-19 03:17:02

问题


I'm writing a C++ function that is templated on type (either float or double), and uses Eigen::Matrix internally. The function will be using a combination of float, double, and templated type Eigen:Matrix objects. Eigen::Matrix<>::cast() works just fine for double and float, though I'm hitting an odd issue when using it with templated types. See code below:

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

Here is the result of compiling:

> 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’

Since I'm only ever instantiating the template with Scalar as a double or float, I'd imagine that the Scalar function calls should have the same effect as the hardcoded float/double types.

Some more system info:

  • Ubuntu 14.04
  • g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2
  • Eigen 3.2.4, downloaded from http://eigen.tuxfamily.org/

Thanks in advance for your help!


回答1:


Thanks, @piotr-s! Looks like this is not an Eigen-specific thing, but more generally just some tricky syntax for calling a templated member functions.

Here's a related question: How to call a template member function?

Here's the answer:

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



来源:https://stackoverflow.com/questions/29754251/issue-casting-c-eigenmatrix-types-via-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!