fork(1) download
  1. #include <iostream>
  2. #include <array>
  3.  
  4. // -- Generate a sequence.
  5. template <int... Is>
  6. struct seq {};
  7. template <int I, int... Is>
  8. struct gen_seq : gen_seq<I - 1, I - 1, Is...> {};
  9. template <int... Is>
  10. struct gen_seq<0, Is...> : seq<Is...> {};
  11.  
  12.  
  13. // -- Array summation function.
  14. template <typename T>
  15. constexpr T sum(std::array<T, 1> arr, decltype(gen_seq<0>{})) {
  16. return std::get<0>(arr);
  17. }
  18.  
  19. template <typename T, std::size_t N, int... Is>
  20. constexpr auto sum(std::array<T, N> arr, seq<Is...>) -> decltype(T() + T()) {
  21. return sum(std::array<T, N - 1>{ { std::get<Is>(arr)... } },
  22. gen_seq<N - 2>()) +
  23. std::get<N - 1>(arr);
  24. }
  25.  
  26. // The interface - sum all elements of a given array.
  27. template <typename T, std::size_t N>
  28. constexpr auto sum(std::array<T, N> arr)
  29. -> decltype(sum(arr, gen_seq<N - 1>{})) {
  30. return sum(arr, gen_seq<N - 1>{});
  31. }
  32.  
  33.  
  34. // -- Demonstration
  35. int main() {
  36. std::cout << sum(std::array<int, 1>{{1}}) << std::endl;
  37. std::cout << sum(std::array<int, 2>{{1, 2}}) << std::endl;
  38. std::cout << sum(std::array<int, 5>{{1, 2, 3, 4, 5}}) << std::endl;
  39. }
Success #stdin #stdout 0s 3296KB
stdin
Standard input is empty
stdout
1
3
15