简体   繁体   中英

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

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 (ie SIZE_ would be initiated by a variable that potentially could have a different value).

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM