I am still new to the Eigen library and C++. I am testing some code and I do not get why this

#include <iostream> #include <Eigen/Dense> using namespace std; int main() { int a = 2; const int SIZE_ = a; Eigen::Matrix<float, SIZE_, SIZE_> test; return 0; } 

does not compile, while this

#include <iostream> #include <Eigen/Dense> using namespace std; int main() { const int SIZE_ = 2; Eigen::Matrix<float, SIZE_, SIZE_> test; return 0; } 

works perfectly fine. How could I change the first code so that it works (i.e. SIZE_ would be initiated by a variable that potentially could have a different value).

2 Answers

You can't. Template arguments must be compile-time constants.

const int SIZE_ = 2; is a compile-time constant, there is no possible way SIZE_ can ever have a value different from 2 here. The compiler knows this and can safely build the type Eigen::Matrix<float, 2, 2>.

const int SIZE_ = someNonConstantExpression; is not a compile-time constant. It cannot be used in template arguments.

You cannot trick the compiler into accepting run-time values where compile-time values are required, such as in templates. However, Eigen has dynamic matrices (where the size need not be known at compile-time) that you could use instead.

I think @MaxLanghof has cleared the problem, but if you still want the value for the Matrix size to come from another method (but still at compile time), you can use a constexpr method like this:

#include <iostream> #include <Eigen/Dense> using namespace std; constexpr int getSizeOfMatrix() { return 2*3; } int main() { const int SIZE_ = getSizeOfMatrix(); Eigen::Matrix<float, SIZE_, SIZE_> test; return 0; } 
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.