简体   繁体   中英

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?

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, ie, 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

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