矩阵推导指南

deduction guides for matrix

我正在寻找初始化矩阵的推导指南。

我已经尝试使用 pack in pack 和 sizeof...initializer_list<initializer_list<T>>、自定义 类 来构造数组,但没有任何效果...

所以,我正在寻找初始化

template <class T, size_t s1, size_t s2>
class matrix
{
T matr[s1][s2]; //maybe with custom array class, if this problem need this
public:
//constructor
};
//deductor

喜欢

matrix m{{1, 2}, {1, 2}};

matrix m({1, 2}, {1, 2});

也许...如果您可以接受在变量构造中添加另一层括号...

matrix m{{{1, 2}, {1, 2}}};
// ......^..............^   another level

你可以构造matrix接收数组的数组,所以Ts1s2会自动推导

template <typename T, std::size_t s1, std::size_t s2>
class matrix
 {
   using ca1 = T const [s1];
   using ca2 = ca1 const [s2];

   T matr[s1][s2];

   public:
   matrix (ca2 & arr2d)
    {
      for ( auto ui = 0u ; ui < s1 ; ++ui )
        for ( auto uj = 0u ; uj < s2 ; ++uj )
           matr[ui][uj] = arr2d[ui][uj];
    }
 };

下面是一个完整的编译示例

#include <iostream>

template <typename T, std::size_t s1, std::size_t s2>
class matrix
 {
   using ca1 = T const [s1];
   using ca2 = ca1 const [s2];

   T matr[s1][s2];

   public:
   matrix (ca2 & arr2d)
    {
      for ( auto ui = 0u ; ui < s1 ; ++ui )
        for ( auto uj = 0u ; uj < s2 ; ++uj )
           matr[ui][uj] = arr2d[ui][uj];
    }
 };

int main()
{
   matrix m{{{1, 2}, {1, 2}, {1, 2}}};
}

我找到了避免额外括号的方法。

这次还需要一个显式推导指南、SFINAE 和一个额外的方法来初始化 matr 成员,但应该可以工作。

下面是完整的例子

#include <iostream>

template <typename T, std::size_t s1, std::size_t s2>
class matrix
 {
   private:
      T matr[s1][s2];

      void init_row (std::size_t i, T const (&arr)[s2])
       {
         for ( auto j = 0u ; j < s2 ; ++j )
            matr[i][j] = arr[j];
       }

   public:
      template <std::size_t ... Dims,
                std::enable_if_t<sizeof...(Dims) == s1, bool> = true,
                std::enable_if_t<((Dims == s2) && ...), bool> = true>
      matrix (T const (&...arrs)[Dims])
       { std::size_t i = -1; (init_row(++i, arrs), ...); }
 };

template <typename T, std::size_t Dim0, std::size_t ... Dims,
          std::enable_if_t<((Dim0 == Dims) && ...), bool> = true>
matrix (T const (&)[Dim0], T const (&...arrs)[Dims])
   -> matrix<T, 1u+sizeof...(Dims), Dim0>;


int main()
{
   matrix m{{1, 2}, {1, 2}, {1, 2}};

   static_assert( std::is_same_v<decltype(m), matrix<int, 3u, 2u>> );
}