| 1 |
// { dg-do run { target c++17 } } |
| 2 |
|
| 3 |
// Copyright (C) 2019-2025 Free Software Foundation, Inc. |
| 4 |
// |
| 5 |
// This file is part of the GNU ISO C++ Library. This library is free |
| 6 |
// software; you can redistribute it and/or modify it under the |
| 7 |
// terms of the GNU General Public License as published by the |
| 8 |
// Free Software Foundation; either version 3, or (at your option) |
| 9 |
// any later version. |
| 10 |
|
| 11 |
// This library is distributed in the hope that it will be useful, |
| 12 |
// but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 |
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 |
// GNU General Public License for more details. |
| 15 |
|
| 16 |
// You should have received a copy of the GNU General Public License along |
| 17 |
// with this library; see the file COPYING3. If not see |
| 18 |
// <http://www.gnu.org/licenses/>. |
| 19 |
|
| 20 |
#include <algorithm> |
| 21 |
#include <testsuite_hooks.h> |
| 22 |
#include <testsuite_iterators.h> |
| 23 |
|
| 24 |
void test01() |
| 25 |
{ |
| 26 |
using __gnu_test::test_container; |
| 27 |
using __gnu_test::input_iterator_wrapper; |
| 28 |
int array[5] = { 1, 2, 3, 4, 5 }; |
| 29 |
test_container<int, input_iterator_wrapper> con(array); |
| 30 |
|
| 31 |
int sum = 0; |
| 32 |
struct Func |
| 33 |
{ |
| 34 |
Func(int& i) : i(i) { } |
| 35 |
Func(Func&&) = default; |
| 36 |
Func& operator=(Func&&) = delete; |
| 37 |
void operator()(int n) const { i += n; } |
| 38 |
int& i; |
| 39 |
}; |
| 40 |
|
| 41 |
struct Size |
| 42 |
{ |
| 43 |
Size(short v) : val(v) { } |
| 44 |
operator short() const { return val; } |
| 45 |
short val; |
| 46 |
}; |
| 47 |
auto res = std::for_each_n(con.begin(), Size(con.size()), Func(sum)); |
| 48 |
|
| 49 |
VERIFY( res == con.end() ); |
| 50 |
VERIFY( sum == 15 ); |
| 51 |
} |
| 52 |
|
| 53 |
void |
| 54 |
test02() |
| 55 |
{ |
| 56 |
using __gnu_test::test_container; |
| 57 |
using __gnu_test::random_access_iterator_wrapper; |
| 58 |
int array[5] = { 2, 4, 6, 8, 10 }; |
| 59 |
test_container<int, random_access_iterator_wrapper> con(array); |
| 60 |
|
| 61 |
int prod = 1; |
| 62 |
struct Func |
| 63 |
{ |
| 64 |
Func(int& i) : i(i) { } |
| 65 |
Func(Func&&) = default; |
| 66 |
Func& operator=(Func&&) = delete; |
| 67 |
void operator()(int n) const { i *= n; } |
| 68 |
int& i; |
| 69 |
}; |
| 70 |
|
| 71 |
struct Size |
| 72 |
{ |
| 73 |
Size(short v) : val(v) { } |
| 74 |
operator short() const { return val; } |
| 75 |
short val; |
| 76 |
}; |
| 77 |
auto res = std::for_each_n(con.begin(), Size(con.size()), Func(prod)); |
| 78 |
|
| 79 |
VERIFY( res == con.end() ); |
| 80 |
VERIFY( prod == 3840 ); |
| 81 |
} |
| 82 |
|
| 83 |
int main() |
| 84 |
{ |
| 85 |
test01(); |
| 86 |
test02(); |
| 87 |
} |