1

I have a question on how to accomplish the following behavior, or if it is even possible in C++. Say I have this variadic function

template<typename T, typename...Pack>
T sum(T a, Pack... pack) {
    return a + sum(pack...);
}

template<typename T>
T sum(T a) {
    return a;
}

and then I have an array

double array[5];

is there a way I could go about doing something like

sum(array[0], array[1], array[2], array[3], array[4]);

without hard coding in each element explicitly? The reason, I am trying to implement something such as,

double array[N];
sum(array[0], array[1], array[2], ..., array[N-1]);

where N is set at compile time.

Barry
  • 286,269
  • 29
  • 621
  • 977
armstrhu
  • 303
  • 3
  • 8

1 Answers1

5

You could, with the help of the index sequence trick:

template <class T, size_t N, size_t... Is>
T array_sum_impl(T (&arr)[N], std::index_sequence<Is...>) {
    return sum(arr[Is]...);
}

template <class T, size_t N>
T array_sum(T (&arr)[N]) {
    return array_sum_impl(arr, std::make_index_sequence<N>{});
}

But it's probably better to just do the normal:

auto sum = std::accumulate(std::begin(array), std::end(array), 0.0);
Barry
  • 286,269
  • 29
  • 621
  • 977
  • I understand expanding Is (such as Is...), but haven't seen something like arr[Is]... before. That is a valid expansion? Also, I am in general not trying to sum things, the summation was just a simple example to allow me to demonstrate the interface I am trying to achieve. – armstrhu Feb 21 '17 at 16:35
  • @armstrhu Yes, you can expand arbitrarily complicated expressions, as long as they're in a context where expansion is allowed. `arr[Is]...` expands to `arr[Is#1], arr[Is#2], ..., arr[Is#N]`. See also [my answer here](http://stackoverflow.com/a/26767333/2069064) and [Nawaz's here](http://stackoverflow.com/a/17652683/2069064) – Barry Feb 21 '17 at 16:38