将一个std::数组拆分为一个较小大小的std::array元组

Spliting a std::array into a tuple of smaller sized std::array

本文关键字:std 一个 array 元组 小大 数组 拆分      更新时间:2023-10-16

我正试图将std::array<T, N>拆分为较小数组的元组,如std::tuple<std::array<T, N1>, std::array<T, N2>, ...>,其中N1 + N2 + ... = N.

namespace detail {
  // Summation of the given values
  template <class T>
  constexpr T sum(const T& x) { return x; }
  template <class T, class ...Args>
  constexpr auto sum(const T& x, Args&&... args)
  { return x + sum(std::forward<Args>(args)...); }
}
template <class T, std::size_t... Ns>
constexpr
std::tuple<std::array<T, Ns>...>
f(const std::array<T, detail::sum(Ns...)>& x)
{
  // How do I implement this function?
}
int main()
{
  constexpr std::array<Foo, 5> arr = { ... };
  constexpr auto t = f<Foo, 2,3>(arr);
}

事实上,我已经实现了f,但它基于一个循环,该循环只是创建一个空数组并复制给定数组的元素,但如果t不是default_constructible,它就不起作用。

我试着使用std::integer_sequencestd::make_index_sequence,但我想我完全迷失了方向。

有人能帮我实现这个功能吗?

写入

template<class T,size_t...Is,size_t N>
std::array<T,sizeof...(Is)>
extract(std::array<T,N>const&,std::index_sequence<Is...>){
  return {{arr[Is]...}};
}

现在我们只需要将{1,2,3}粗略地转换为{{0},{1,2},{3,4,5}},所有内容都是C++索引序列(所以语法)。

{3,4,0}映射到{0,1,2}——子数组的索引计数。然后将CCD_ 12 x 1映射到CCD_。这给了我们子数组中的索引,我们将其提供给extract,bob是你的叔叔。

template<size_t n, size_t...counts>
constexpr auto
foo( std::index_sequence<counts...> )
->  offset_seq<
  sum_n<n>(counts...),
  std::make_index_sequence<get_n<n,counts...> >
>{ return {}; }

例如{3,4,0} x 1{3,4,5,6}部分。