How to fix 'non-type template argument is not a constant expression' in eigen3?
Asked Answered
K

2

11

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).

Kilmer answered 23/10, 2019 at 12:1 Comment(0)
D
8

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.

Donny answered 23/10, 2019 at 12:46 Comment(0)
W
3

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;
}
Winglet answered 23/10, 2019 at 15:36 Comment(1)
I would really suggest writing constexpr int SIZE_ = ... so you immediately get the error (in case getSizeOfMatrix() was not constexpr) and not only when trying to declare test.Muddle

© 2022 - 2024 — McMap. All rights reserved.