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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With