简体   繁体   English

如何将向量元素作为参数传递给可变参数模板函数?

[英]How to pass vector elements as arguments to variadic template function?

So, let's say I have this code: 所以,假设我有这个代码:

template <class T1, class T2>
auto sum(T1 a, T2 b) ->decltype(a + b) {
    return a + b;
}
template <class T1, class T2, class... T3>
auto sum(T1 a, T2 b, T3... tail) ->decltype(a + sum(b, tail...)) {
    return a + sum(b, tail...);
}

I would like to call function sum in a way I pass a vector: 我希望以传递向量的方式调用函数sum

vector<double> numbers = { 1, 2, 6, 5 };

that should be used as a list of arguments for function sum . 应该用作函数sum的参数列表。 How can I do that? 我怎样才能做到这一点? Calling function sum should return 14 in this case. 在这种情况下,调用函数sum应该返回14。

std::vector is a run-time beast. std::vector是一个运行时的野兽。 That is, it allocates its buffer on the heap and generally any manipulation is allowed during run-time. 也就是说,它在堆上分配缓冲区,通常在运行时允许任何操作。 On the other hand variadic template "pealing" is done during compile time. 另一方面,可变参数模板“pealing”在编译期间完成。 Consequently, a std::vector and variadic templates are somewhat "disjoint". 因此, std::vector和variadic模板有点“不相交”。 Thus, it's not possible to do what you want with a vector. 因此,用矢量做你想做的事是不可能的。

If you want to sum the elements of a vector this can be done in run-time using std::accumulate : 如果要对向量的元素求和,可以使用std::accumulate在运行时完成:

std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = std::accumulate(v.begin(), v.end(), 0);

As Brian mentioned in the comments you could use a std::array for compile time computation in combination with constexpr functions. 正如Brian在评论中提到的,你可以使用std::array进行编译时计算以及constexpr函数。 An example of how you could do this is displayed below: 下面显示了如何执行此操作的示例:

namespace detail {
template <class T1, class T2>
constexpr auto sum_(T1 a, T2 b) {
    return a + b;
}
template <class T1, class T2, class... T3>
constexpr auto sum_(T1 a, T2 b, T3... tail) {
    return a + sum_(b, tail...);
}

template <typename T, std::size_t N, std::size_t... Is>
constexpr T sum_impl(std::array<T, N> const &src, std::index_sequence<Is...>) {
  return sum_(src[Is]...);
}

}

template <typename T, std::size_t N>
constexpr T sum(std::array<T, N> const &arr) {
  return detail::sum_impl(arr, std::make_index_sequence<N>{});
}

Live Demo 现场演示

In the above example I marked your sum functions constexpr . 在上面的例子中,我标记了你的sum函数constexpr You can also figure out how you can use std::make_index_sequence to feed the elements of your array as arguments to your variadic sum function. 您还可以弄清楚如何使用std::make_index_sequence将数组元素作为变量sum函数的参数提供。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM