Search code examples
c++matrixlinear-algebran-dimensional

N-dimensional matrix class using vectors of vectors


I am trying to implement a custom class which handles n-dimensional matrices using vectors of vectors, generalizing the 1d, 2d and 3d definitions:

using mat1dd = std::vector<double>;
using mat2dd = std::vector<mat1dd>;
using mat3dd = std::vector<mat2dd>;

Here is my attempt to implement this class.

template <std::size_t N_DIM, typename T>
class matnd {
    std::vector<matnd<N_DIM - 1, T>> mat;
    ...
}

My intention is that, for example,

matnd<3, double> mat;

creates a 3-dimensional matrix of doubles.

The recursive definition above clearly fails because it has no base case, so N_DIM just decreases indefinitely (until the compiler halts). How could I implement this class in such a way that I do not encounter this problem?


Solution

  • Use a template struct holding the type definition specialize it for 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>;