本文介绍了附加到std :: array的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于找不到(错误地?)这样的函数,我试图制作一个编译时函数( constexpr ),该函数需要一个 std :: array< T,n> arr T t 并返回一个新的 std :: array< T,n + 1> arr 的末尾加上了 t 的$ c>。我从这样的事情开始:

Since I was not able to find such a function (incorrectly?), I'm trying to make a compile-time function (constexpr) function which takes a std::array<T,n> arr and a T t and returns a new std::array<T,n+1> with t added to the end of arr. I've started with something like this:

template <typename T, int n>
constexpr std::array<T,n+1> append(std::array<T,n> a, T t);

template <typename T>
constexpr std::array<T,1> append(std::array<T,0> a, T t)
{
  return std::array<T,1>{t};
}

template <typename T>
constexpr std::array<T,2> append(std::array<T,1> a, T t)
{
  return std::array<T,2>{a[0], t};
}

在这里我被卡住了。我需要的是在初始值设定项列表的前 n 个地方扩展 a 的方法,然后添加 t 添加结尾。那可能吗?还是有另一种方法?

Here I get stuck. What I need is a way to expand a in the first n places of the initializer list, and then add t add the end. Is that possible? Or is there another way of doing this?

推荐答案

当然,有可能: std :: index_sequence< I ...> 是你的朋友!您只需将其分派到一个函数,该函数将一个合适的 std :: index_sequence< I ...> 作为参数,并使用所有值扩展该包。例如:

Of course, it is possible: std::index_sequence<I...> is your friend! You'd simply dispatch to a function which takes a suitable std::index_sequence<I...> as argument and expands the pack with all the values. For example:

template <typename T, std::size_t N, std::size_t... I>
constexpr std::array<T, N + 1>
append_aux(std::array<T, N> a, T t, std::index_sequence<I...>) {
    return std::array<T, N + 1>{ a[I]..., t };
}
template <typename T, std::size_t N>
constexpr std::array<T, N + 1> append(std::array<T, N> a, T t) {
    return append_aux(a, t, std::make_index_sequence<N>());
}

这篇关于附加到std :: array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 02:59