Search code examples
c++stdarray

Declaring 2 (or even multi-) dimensional std::arrays elegantly


I'm using 2-dimensional arrays based on std::array.

Basically instead of:

MyType myarray[X_SIZE][Y_SIZE];

I have:

std::array<std::array<MyType, Y_SIZE>, X_SIZE> myarray;

This works perfectly fine but IMO the declaration is not very readable.

Is there a way to declare this using some clever C++ template mecanism, so the declaration could look something like this?

My2DArray<Mytype, X_SIZE, Y_SIZE> myarray;

Solution

  • If you want just 2D arrays, it's fairly straightforward:

    template <class T, std::size_t X, std::size_t Y>
    using My2DArray = std::array<std::array<T, Y>, X>;
    

    If you want a generic mechanism not limited to 2D arrays, it can be done too:

    template <class T, std::size_t N, std::size_t... Ns>
    struct AddArray {
        using type = std::array<typename AddArray<T, Ns...>::type, N>;
    };
    
    template <class T, std::size_t N>
    struct AddArray<T, N> {
        using type = std::array<T, N>;
    };
    
    template <class T, std::size_t... N>
    using MyNDArray = typename AddArray<T, N...>::type;
    

    [Live example]