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

标签 c++ templates alias eigen

我正在编写一个简单的程序来定义具有表示状态的 vector 的系统。我希望有一个 Eigen vector 的声明类型,具体取决于派生类中的状态数。

我尝试在别名上使用模板来实现这一点,类似于下面显示的代码

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

我最终想要一个可以在派生类中使用的类型。这可能吗?

最佳答案

通过两个小改动,您的代码可以正常工作。

首先,这里不能有typename关键字:

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

其次,NUM_STATES 必须是编译时常量,即,将其声明为 enum 的元素或声明为 static const int (或 static constexpr int,如果您愿意):

static const int NUM_STATES = 5;

godbolt 的完整工作示例:https://godbolt.org/z/_T0gix

关于c++ - 使用模板的动态特征声明类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56763047/

相关文章:

c++ - 模态对话框不会作为最顶层窗口打开

c++ - 如何在表示整数数据结构的类上定义函数

eval - 为 `git commit` 创建别名接受 N 个任意 `-m` 参数

c++ - 在 C++ 控制台应用程序中编写位图

c++ - 使用 initializer_list 上的数据

angularjs - Angular : difference when using template or templateUrl

c# - 带别名的 Linq

apache - JBoss 4.2.3 中的文件服务?

c++ - 使用 UML 工具理解 C++ 代码库

c++ - 将可变函数作为参数传递