fork download
  1. #include <iostream>
  2. #include <functional>
  3. #include <initializer_list>
  4.  
  5. template<typename Functor, typename T, size_t N>
  6. T constexpr reduce(Functor f, T(&arr)[N]) {
  7. typename std::remove_const<T>::type val = arr[0];
  8. for(auto i = std::begin(arr)+1; i != std::end(arr); ++i) val = f(val, *i);
  9. return val;
  10. }
  11.  
  12. template<typename Functor, typename T>
  13. T constexpr reduce(Functor f, std::initializer_list<T> il) {
  14. T val = *il.begin();
  15. for(auto i = il.begin()+1; i != il.end(); ++i) val = f(val, *i);
  16. return val;
  17. }
  18.  
  19. template<typename Functor, typename T, typename... Ts>
  20. T constexpr reduce(Functor f, T t1, Ts... ts) {
  21. return f(t1, reduce(f, std::initializer_list<T>({ts...})));
  22. }
  23.  
  24. template<int value>
  25. void print_constexpr() { std::cout << value << std::endl; }
  26.  
  27. int main() {
  28. // run-time or compile-time
  29. std::cout << reduce(std::plus<int>(), 1, 2, 3, 4, 5, 6, 7) << std::endl; // 28
  30. std::cout << reduce(std::plus<int>(), {1, 2, 3, 4, 5, 6, 7}) << std::endl;// 28
  31. const int input[3] = {1, 2, 3}; // 6
  32. std::cout << reduce(std::plus<int>(), input) << std::endl;
  33.  
  34. // compile-time
  35. print_constexpr< reduce(std::plus<int>(), 1, 2, 3, 4, 5, 6, 7) >(); // 28
  36. print_constexpr< reduce(std::plus<int>(), {1, 2, 3, 4, 5, 6, 7}) >(); // 28
  37. constexpr int input_constexpr[3] = {1, 2, 3}; // 6
  38. print_constexpr< reduce(std::plus<int>(), input_constexpr) >(); // 6
  39.  
  40. return 0;
  41. }
Success #stdin #stdout 0s 3412KB
stdin
Standard input is empty
stdout
28
28
6
28
28
6