Reputation: 111
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).
Upvotes: 11
Views: 13225
Reputation: 8427
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;
}
Upvotes: 3
Reputation: 23691
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.
Upvotes: 9