我正在编写一个根据类型(float
或 double
)模板化并使用 Eigen::Matrix
的 C++ 函数在内部。该函数将使用 float
的组合, double
, 和模板化类型 Eigen:Matrix
对象。 Eigen::Matrix<>::cast()
适用于 double
和 float
,尽管我在将它与模板化类型一起使用时遇到了一个奇怪的问题。见下面的代码:
#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
实例化模板作为double
或 float
,我想 Scalar
函数调用应具有与硬编码相同的效果 float
/double
类型。
一些更多的系统信息:
- Ubuntu 14.04
- g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2
- Eigen 3.2.4,下载自 http://eigen.tuxfamily.org/
预先感谢您的帮助!
最佳答案
谢谢,@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/