How to pass vector elements as arguments to variadic template function?

本小妞迷上赌 提交于 2019-12-10 13:38:48

问题


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:

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

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.


回答1:


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.

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

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

Live Demo

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.



来源:https://stackoverflow.com/questions/34233797/how-to-pass-vector-elements-as-arguments-to-variadic-template-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!