【问题标题】:deduction guides for matrix矩阵的推导指南
【发布时间】:2019-09-12 08:46:14
【问题描述】:

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

我尝试使用 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});

【问题讨论】:

  • {/*..*/} 的问题是它没有类型(或者intializer_list 没有编译时间大小)。
  • matrix m{std::array{1, 2}, std::array{1, 2}}; 可能是可能的。

标签: c++ matrix c++17 template-argument-deduction


【解决方案1】:

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

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

【讨论】:

  • 你试过了吗?您使用什么扣除指南?我认为演绎指南根本不适用于这种语法。
  • @bolov - 我已经尝试过使用 g++ 和 clang++。
  • 它有效:Demo。使用的 CTAD 是默认的,因为 max66 提供了构造函数。
  • 哦,没有明确的演绎指南。我明白了。
  • @bolov - 添加了一个完整的编译示例(但很简单)
【解决方案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>> );
}

【讨论】:

    猜你喜欢
    • 2023-04-04
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    相关资源
    最近更新 更多