xref: /llvm-project/libcxx/test/std/algorithms/alg.modifying.operations/alg.generate/generate_n.pass.cpp (revision 6b1ae9b854bd186c8dab4784d287f38ce61459d2)
1 //===----------------------------------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is dual licensed under the MIT and the University of Illinois Open
6 // Source Licenses. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 // <algorithm>
11 
12 // template<class Iter, IntegralLike Size, Callable Generator>
13 //   requires OutputIterator<Iter, Generator::result_type>
14 //         && CopyConstructible<Generator>
15 //   constexpr void      // constexpr after c++17
16 //   generate_n(Iter first, Size n, Generator gen);
17 
18 #ifdef _MSC_VER
19 #pragma warning(disable: 4244) // conversion from 'const double' to 'int', possible loss of data
20 #endif
21 
22 #include <algorithm>
23 #include <cassert>
24 
25 #include "test_macros.h"
26 #include "test_iterators.h"
27 #include "user_defined_integral.hpp"
28 
29 struct gen_test
30 {
31     TEST_CONSTEXPR int operator()() const {return 2;}
32 };
33 
34 
35 #if TEST_STD_VER > 17
36 TEST_CONSTEXPR bool test_constexpr() {
37     const size_t N = 5;
38     int ib[] = {0, 0, 0, 0, 0, 0}; // one bigger than N
39 
40     auto it = std::generate_n(std::begin(ib), N, gen_test());
41 
42     return it == (std::begin(ib) + N)
43         && std::all_of(std::begin(ib), it, [](int x) { return x == 2; })
44         && *it == 0 // don't overwrite the last value in the output array
45         ;
46     }
47 #endif
48 
49 
50 template <class Iter, class Size>
51 void
52 test2()
53 {
54     const unsigned n = 4;
55     int ia[n] = {0};
56     assert(std::generate_n(Iter(ia), Size(n), gen_test()) == Iter(ia+n));
57     assert(ia[0] == 2);
58     assert(ia[1] == 2);
59     assert(ia[2] == 2);
60     assert(ia[3] == 2);
61 }
62 
63 template <class Iter>
64 void
65 test()
66 {
67     test2<Iter, int>();
68     test2<Iter, unsigned int>();
69     test2<Iter, long>();
70     test2<Iter, unsigned long>();
71     test2<Iter, UserDefinedIntegral<unsigned> >();
72     test2<Iter, float>();
73     test2<Iter, double>();  // this is PR#35498
74     test2<Iter, long double>();
75 }
76 
77 int main()
78 {
79     test<forward_iterator<int*> >();
80     test<bidirectional_iterator<int*> >();
81     test<random_access_iterator<int*> >();
82     test<int*>();
83 
84 #if TEST_STD_VER > 17
85     static_assert(test_constexpr());
86 #endif
87 }
88