如何将向量元素作为可变参数模板函数的参数传递? [英] How to pass vector elements as arguments to variadic template function?

查看:98
本文介绍了如何将向量元素作为可变参数模板函数的参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,假设我有以下代码:

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

我想调用函数 sum 以某种方式传递向量:

I would like to call function sum in a way I pass a vector:

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

应用作函数 sum 。我怎样才能做到这一点?在这种情况下,调用函数 sum 应该返回14。

that should be used as a list of arguments for function sum. How can I do that? Calling function sum should return 14 in this case.

推荐答案

std :: vector 是运行时的野兽。也就是说,它在堆上分配其缓冲区,并且通常在运行时允许任何操作。另一方面,可变参数模板 pearing在编译时完成。因此, std :: vector 和可变参数模板有些不相交。因此,不可能对向量进行任何操作。

std::vector is a run-time beast. 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. Consequently, a std::vector and variadic templates are somewhat "disjoint". Thus, it's not possible to do what you want with a vector.

如果要对向量的元素求和,可以使用<$在运行时完成c $ c> std :: accumulation

If you want to sum the elements of a vector this can be done in run-time using 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);

正如Brian在评论中提到的那样,您可以使用 std :: array constexpr 函数结合使用进行编译时计算。下面显示了如何执行此操作的示例:

As Brian mentioned in the comments you could use a std::array for compile time computation in combination with constexpr functions. 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>{});
}

实时演示

在上面的示例中,我标记了您的总和函数 constexpr 。您还可以弄清楚如何使用 std :: make_index_sequence 将数组的元素作为变量来填充 sum 函数。

In the above example I marked your sum functions 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.

这篇关于如何将向量元素作为可变参数模板函数的参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆