我正在编写一个在类型上模板化的C ++函数(float
或double
),并在内部使用Eigen::Matrix
。该函数将使用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
类型具有相同的效果。
更多系统信息:
提前感谢您的帮助!
答案 0 :(得分:6)
谢谢,@ piotr-s!看起来这不是特定于特定的东西,但更一般地说只是调用模板化成员函数的一些棘手的语法。
以下是相关问题:How to call a template member function?
以下是答案:
mat_d = mat_s.template cast<double>();