c++ - 使用向量的向量的 N 维矩阵类
问题描述
我正在尝试实现一个自定义类,该类使用向量的向量处理 n 维矩阵,概括 1d、2d 和 3d 定义:
using mat1dd = std::vector<double>;
using mat2dd = std::vector<mat1dd>;
using mat3dd = std::vector<mat2dd>;
这是我实现这个类的尝试。
template <std::size_t N_DIM, typename T>
class matnd {
std::vector<matnd<N_DIM - 1, T>> mat;
...
}
我的意图是,例如,
matnd<3, double> mat;
创建一个双精度的 3 维矩阵。
上面的递归定义显然失败了,因为它没有基本情况,所以N_DIM
只是无限期地减少(直到编译器停止)。我怎样才能以不遇到这个问题的方式实现这个类?
解决方案
使用包含类型定义的模板结构将其专门用于n = 1
:
template<size_t n, typename T>
struct matnd_helper
{
using type = std::vector<typename matnd_helper<n - 1, T>::type>;
};
template<typename T>
struct matnd_helper<1, T>
{
using type = std::vector<T>;
};
template<size_t n, typename T>
using matnd = typename matnd_helper<n, T>::type;
using mat1dd = matnd<1, double>;
using mat2dd = matnd<2, double>;
using mat3dd = matnd<3, double>;
推荐阅读
- c# - 在 XAML 中包装属性
- applescript - 使用带有 applescript 和 novation 启动板的 midipipe 控制 OBS
- javascript - 如何在 React Native 中绘制六边形图像
- reactjs - useEffect 和 ESlint 穷举-deps 规则
- python - Spark.sql:删除列名上的表名
- c# - 正则表达式匹配无法在两个字符之间找到文本
- r - 使两个输入相互依赖
- python - Discord.py 上 SQLite 3 的排序问题
- typescript - 使用纱线工作区从文件中解析而不是在 Lerna monorepo 中输入
- python - 多列合二为一