基于 std::array 的多维数组

multi-dimensional array based on std::array

本文关键字:数组 array std 基于      更新时间:2023-10-16

我需要一个基于std::array给出多维数组的模板。

template <typename T, size_t...>
using MyArray = ? // -> here is something I don't know how to write...

用法如下:

static_assert(std::is_same_v<
MyArray<int, 2>, std::array<int, 2>
>);
static_assert(std::is_same_v<
MyArray<int, 2, 3>, std::array<std::array<int, 3>, 2>
>);  // the dimension should be the opposite order
MyArray a;    // a stacked 2-D array of size 2x3
a[0][2] = 2;  // valid index

任何帮助将不胜感激!

我不知道如何只用一个using来制作它;我能想象到的最好的需要辅助结构的帮助。

如下内容

template <typename, std::size_t ...>
struct MyArrayHelper;
template <typename T, std::size_t D0, std::size_t ... Ds>
struct MyArrayHelper<T, D0, Ds...>
{ using type = std::array<typename MyArrayHelper<T, Ds...>::type, D0>; };
template <typename T>
struct MyArrayHelper<T>
{ using type = T; };
template <typename T, std::size_t ... Ds>
using MyArray = typename MyArrayHelper<T, Ds...>::type;