简体   繁体   English

使用模板的动态特征声明类型

[英]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:首先,这里不能有typename关键字:

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):其次, NUM_STATES必须是编译时常量,即,将其声明为enum元素或static const int (或static constexpr int ,如果您愿意):

static const int NUM_STATES = 5;

Full working example on godbolt: https://godbolt.org/z/_T0gix关于 Godbolt 的完整工作示例: https ://godbolt.org/z/_T0gix

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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