Search code examples
c++arraystemplatesvariadic-templates

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


How can I create a multi dimensional std::array of type Type with (of course) known initial constexpr dimensions with some smart variadic template "MDA".

The number of dimensions shall be variable.

In the end I want to be able to write:

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

and the result should be equal to

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

And save a lot of (complicated, or even error prone) typing work . . .


Edit:

I am not sure if this possible at all. But what I am looking for, is some "typing saver", maybe in conjunction with a using statement.


Solution

  • Certainly possible with use of helper class templates, C++11 (except the static assert part)

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