1 //===----------------------------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 // <numeric> 10 // UNSUPPORTED: c++98, c++03, c++11, c++14 11 12 // template<class InputIterator, class T, class BinaryOperation> 13 // T reduce(InputIterator first, InputIterator last, T init, BinaryOperation op); 14 15 #include <numeric> 16 #include <cassert> 17 18 #include "test_iterators.h" 19 20 template <class Iter, class T, class Op> 21 void 22 test(Iter first, Iter last, T init, Op op, T x) 23 { 24 static_assert( std::is_same_v<T, decltype(std::reduce(first, last, init, op))>, "" ); 25 assert(std::reduce(first, last, init, op) == x); 26 } 27 28 template <class Iter> 29 void 30 test() 31 { 32 int ia[] = {1, 2, 3, 4, 5, 6}; 33 unsigned sa = sizeof(ia) / sizeof(ia[0]); 34 test(Iter(ia), Iter(ia), 0, std::plus<>(), 0); 35 test(Iter(ia), Iter(ia), 1, std::multiplies<>(), 1); 36 test(Iter(ia), Iter(ia+1), 0, std::plus<>(), 1); 37 test(Iter(ia), Iter(ia+1), 2, std::multiplies<>(), 2); 38 test(Iter(ia), Iter(ia+2), 0, std::plus<>(), 3); 39 test(Iter(ia), Iter(ia+2), 3, std::multiplies<>(), 6); 40 test(Iter(ia), Iter(ia+sa), 0, std::plus<>(), 21); 41 test(Iter(ia), Iter(ia+sa), 4, std::multiplies<>(), 2880); 42 } 43 44 template <typename T, typename Init> 45 void test_return_type() 46 { 47 T *p = nullptr; 48 static_assert( std::is_same_v<Init, decltype(std::reduce(p, p, Init{}, std::plus<>()))>, "" ); 49 } 50 51 int main(int, char**) 52 { 53 test_return_type<char, int>(); 54 test_return_type<int, int>(); 55 test_return_type<int, unsigned long>(); 56 test_return_type<float, int>(); 57 test_return_type<short, float>(); 58 test_return_type<double, char>(); 59 test_return_type<char, double>(); 60 61 test<input_iterator<const int*> >(); 62 test<forward_iterator<const int*> >(); 63 test<bidirectional_iterator<const int*> >(); 64 test<random_access_iterator<const int*> >(); 65 test<const int*>(); 66 67 // Make sure the math is done using the correct type 68 { 69 auto v = {1, 2, 3, 4, 5, 6, 7, 8}; 70 unsigned res = std::reduce(v.begin(), v.end(), 1U, std::multiplies<>()); 71 assert(res == 40320); // 8! will not fit into a char 72 } 73 74 return 0; 75 } 76