问题
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