Search code examples
c++arraysconstructorc++14variadic-templates

initialize double nested std::array from variadic template array reference constructor


Problem

I have a Matrix class that is able to do some math. It holds its data in a double nested std::array as a variable. I have a constructor that takes an array reference as a variadic template. I did this so i could add some SFINAE more easily (omitted here).

#include <array>

template <std::size_t N, std::size_t M, typename T>
class Matrix{
  public:

    template <typename... TArgs>
    Matrix(TArgs const(&&... rows)[M]) {
        // ??
    }

  // ...

  private:
    std::array<std::array<T,M>, N> data;
};

Question

How can i initialize the double nested array inside the constructor?


Solution

  • With the not shown constraint than sizeof..(TArgs) == N and types are T, you might store address of rows in array pointer and then work normally

    template <typename... TArgs>
    Matrix(TArgs const(&&... rows)[M]) {
        using Arr = const T (*)[M];
        const Arr args[N] = {&rows...}; // or const T (*args[N])[M] = {&rows...};
    
        for (std::size_t i = 0; i != N; ++i) {
            for (std::size_t j = 0; j != M; ++j) {
                data[i][j] = (*args[i])[j];
            }
        }
    }
    

    Demo