Using a global variable to initialize an identity matrix not working

Viewed 365

I would like to use a global variable n = 7 to initialize a 7x7 identity matrix, as shown in the code below:

#include <iostream>
#include <Eigen/Dense>

using namespace std;
using namespace Eigen;
using Eigen::MatrixXd;

int n = 7;

int main()
{
        MatrixXd I = Matrix<double, n, n>::Identity();
        cout << I << endl;
}

When compiling, I get error: the variable n is not usable in a constant expression. Is there any way to use a global variable for initializing the identity matrix?

1 Answers

As the error message states, you need a compile time constant.

You can make n that by using constexpr

#include <iostream>
#include <Eigen/Dense>

using namespace std;
using namespace Eigen;
using Eigen::MatrixXd;

constexpr int n = 7;

int main()
{
        MatrixXd I = Matrix<double, n, n>::Identity();
        cout << I << endl;
}
Related