【发布时间】:2019-03-30 11:48:06
【问题描述】:
为了从 MATLAB 程序中读取和存储一些结果,我需要使用多达 6 维矩阵。而不是做类似的事情:
typedef std::vector<double> Row;
typedef std::vector<Row> Matrix2;
typedef std::vector<Matrix2> Matrix3;
typedef std::vector<Matrix3> Matrix4;
typedef std::vector<Matrix4> Matrix5;
typedef std::vector<Matrix5> Matrix6;
我决定使用模板,这就是我目前所拥有的:
template <class T, int N>
class Matrix {
public:
typedef typename Matrix<T, N - 1>::type MatrixOneDimLower;
typedef std::vector<MatrixOneDimLower> type;
type _data;
template <unsigned int dn, typename ...NT>
Matrix(unsigned int dn, NT ...drest) : _data(dn, MatrixOneDimLower(drest)) {}
MatrixOneDimLower& operator[](unsigned int index)
{
return _data[index];
}
};
template <class T>
class Matrix<T, 1> {
public:
typedef std::vector<T> type;
type _data;
Matrix(unsigned int d0) : _data(d0, T(0.0)) {}
T& operator[](unsigned int index)
{
return _data[index];
}
};
不幸的是,我不太擅长可变参数模板和递归模板,这不起作用。例如,如果我尝试将其用作:
Matrix<double, 4> temp(n, dim[2], dim[1], dim[0]);
我收到此编译时错误(Visual Studio 2017):
error C2661: 'Matrix<double,4>::Matrix': no overloaded function takes 4 arguments
如果您能告诉我我做错了什么,我将不胜感激。
【问题讨论】:
-
你真的不想要很多嵌套向量。请参阅我的答案here 的下半部分,了解原因以及如何解决该问题的玩具示例。
-
我认为正确的术语是“六阶张量”。
标签: c++ templates variadic-templates