rsvar67
rsvar67

Reputation: 77

Dynamic eigen declaration types using templates

I am writing a simple program to define systems that has vectors representing the states. I would like to have a declaration type of the vector of Eigen depending on the number of states in the derived class.

I tried to achieve this using templates on aliases, something like the code shown below

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

using  namespace std;
using  namespace Eigen;

class A
{
public:
    template <int T>
    using StateVector = typename Matrix<double, T, 1>;
};

class B : public A
{
public:
    int NUM_STATES = 5;
    B(){
        StateVector<NUM_STATES> a;
        a.setIdentity();
        cout<<a<<endl;
    }
};

int main(){
    B b;
}

I ultimately want to have a type that can be used in the derived classes. Is this possible?

Upvotes: 1

Views: 116

Answers (1)

chtz
chtz

Reputation: 18807

With two minor changes, your code works fine.

First, there must be no typename keyword here:

template <int T>
using StateVector = Matrix<double, T, 1>;

Second, NUM_STATES must be a compile-time constant, i.e., either declare it as element of an enum or as static const int (or static constexpr int, if you prefer):

static const int NUM_STATES = 5;

Full working example on godbolt: https://godbolt.org/z/_T0gix

Upvotes: 1

Related Questions