如何使用模板创建多维std::array?

How to create a multi dimensional std::array using a template?

如何使用一些智能可变参数模板“MDA”创建一个 Type 类型的多维 std::array,(当然)已知初始 constexpr 维。

维数应该是可变的。

最后我希望能够这样写:

MDA<int,3,4,5,6> a4d{};

结果应该等于

std::array < std::array < std::array < std::array<int, 6> , 5 > , 4 > , 3 > a4d{};

并节省大量(复杂的,甚至容易出错的)打字工作。 . .


编辑:

我完全不确定这是否可行。但我正在寻找的是一些“打字保护程序”,可能与 using 语句结合使用。

你可以使用所谓的meta-functions

template<class T, int N, int... M>
struct MDA_struct
{
    using type = std::array<typename MDA_struct<T, M...>::type, N>;
};

template<class T, int N>
struct MDA_struct<T, N>
{
    using type = std::array<T, N>;
};

template<class T, int... N>
using MDA = typename MDA_struct<T, N...>::type;

当然可以使用助手 class 模板,C++11(静态断言部分除外)

#include <array>

template<typename T, std::size_t Head, std::size_t... Tail>
struct MDA_impl{
    using type = std::array<typename MDA_impl<T, Tail...>::type, Head>;
};
// Base specialization
template<typename T, std::size_t N>
struct MDA_impl<T,N>{
    using type = std::array<T, N>;
};

template<typename T, std::size_t... Ns>
using MDA = typename MDA_impl<T,Ns...>::type;

int main(){
    static_assert(std::is_same_v<MDA<int,3,4,5,6>,
                  std::array<std::array<std::array<std::array<int, 6>,5>,4>,3>>);
}