xref: /llvm-project/libcxx/test/std/numerics/numeric.ops/reduce/reduce_init.pass.cpp (revision 5425106e493e26f7e0a87077c8eca657a9aff293)
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 // UNSUPPORTED: c++03, c++11, c++14
10 
11 // <numeric>
12 
13 // Became constexpr in C++20
14 // template<class InputIterator, class T>
15 //   T reduce(InputIterator first, InputIterator last, T init);
16 
17 #include <numeric>
18 #include <cassert>
19 
20 #include "test_macros.h"
21 #include "test_iterators.h"
22 
23 template <class Iter, class T>
24 TEST_CONSTEXPR_CXX20 void
test(Iter first,Iter last,T init,T x)25 test(Iter first, Iter last, T init, T x)
26 {
27     static_assert( std::is_same_v<T, decltype(std::reduce(first, last, init))> );
28     assert(std::reduce(first, last, init) == x);
29 }
30 
31 template <class Iter>
32 TEST_CONSTEXPR_CXX20 void
test()33 test()
34 {
35     int ia[] = {1, 2, 3, 4, 5, 6};
36     unsigned sa = sizeof(ia) / sizeof(ia[0]);
37     test(Iter(ia), Iter(ia), 0, 0);
38     test(Iter(ia), Iter(ia), 1, 1);
39     test(Iter(ia), Iter(ia+1), 0, 1);
40     test(Iter(ia), Iter(ia+1), 2, 3);
41     test(Iter(ia), Iter(ia+2), 0, 3);
42     test(Iter(ia), Iter(ia+2), 3, 6);
43     test(Iter(ia), Iter(ia+sa), 0, 21);
44     test(Iter(ia), Iter(ia+sa), 4, 25);
45 }
46 
47 template <typename T, typename Init>
48 TEST_CONSTEXPR_CXX20 void
test_return_type()49 test_return_type()
50 {
51     T *p = nullptr;
52     static_assert( std::is_same_v<Init, decltype(std::reduce(p, p, Init{}))> );
53 }
54 
55 TEST_CONSTEXPR_CXX20 bool
test()56 test()
57 {
58     test_return_type<char, int>();
59     test_return_type<int, int>();
60     test_return_type<int, unsigned long>();
61     test_return_type<float, int>();
62     test_return_type<short, float>();
63     test_return_type<double, char>();
64     test_return_type<char, double>();
65 
66     test<cpp17_input_iterator<const int*> >();
67     test<forward_iterator<const int*> >();
68     test<bidirectional_iterator<const int*> >();
69     test<random_access_iterator<const int*> >();
70     test<const int*>();
71 
72     return true;
73 }
74 
main(int,char **)75 int main(int, char**)
76 {
77     test();
78 #if TEST_STD_VER > 17
79     static_assert(test());
80 #endif
81     return 0;
82 }
83