xref: /llvm-project/libcxx/include/__iterator/next.h (revision e9c0c6604e47a7cda323544217c056f7f5aec888)
1 // -*- C++ -*-
2 //===----------------------------------------------------------------------===//
3 //
4 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5 // See https://llvm.org/LICENSE.txt for license information.
6 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #ifndef _LIBCPP___ITERATOR_NEXT_H
11 #define _LIBCPP___ITERATOR_NEXT_H
12 
13 #include <__assert>
14 #include <__config>
15 #include <__iterator/advance.h>
16 #include <__iterator/concepts.h>
17 #include <__iterator/incrementable_traits.h>
18 #include <__iterator/iterator_traits.h>
19 #include <__type_traits/enable_if.h>
20 
21 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
22 #  pragma GCC system_header
23 #endif
24 
25 _LIBCPP_BEGIN_NAMESPACE_STD
26 
27 template <class _InputIter, __enable_if_t<__has_input_iterator_category<_InputIter>::value, int> = 0>
28 [[__nodiscard__]] inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX17 _InputIter
29 next(_InputIter __x, typename iterator_traits<_InputIter>::difference_type __n = 1) {
30   // Calling `advance` with a negative value on a non-bidirectional iterator is a no-op in the current implementation.
31   // Note that this check duplicates the similar check in `std::advance`.
32   _LIBCPP_ASSERT_PEDANTIC(__n >= 0 || __has_bidirectional_iterator_category<_InputIter>::value,
33                           "Attempt to next(it, n) with negative n on a non-bidirectional iterator");
34 
35   std::advance(__x, __n);
36   return __x;
37 }
38 
39 #if _LIBCPP_STD_VER >= 20
40 
41 // [range.iter.op.next]
42 
43 namespace ranges {
44 struct __next {
45   template <input_or_output_iterator _Ip>
46   [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr _Ip operator()(_Ip __x) const {
47     ++__x;
48     return __x;
49   }
50 
51   template <input_or_output_iterator _Ip>
52   [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr _Ip operator()(_Ip __x, iter_difference_t<_Ip> __n) const {
53     ranges::advance(__x, __n);
54     return __x;
55   }
56 
57   template <input_or_output_iterator _Ip, sentinel_for<_Ip> _Sp>
58   [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr _Ip operator()(_Ip __x, _Sp __bound_sentinel) const {
59     ranges::advance(__x, __bound_sentinel);
60     return __x;
61   }
62 
63   template <input_or_output_iterator _Ip, sentinel_for<_Ip> _Sp>
64   [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr _Ip
65   operator()(_Ip __x, iter_difference_t<_Ip> __n, _Sp __bound_sentinel) const {
66     ranges::advance(__x, __n, __bound_sentinel);
67     return __x;
68   }
69 };
70 
71 inline namespace __cpo {
72 inline constexpr auto next = __next{};
73 } // namespace __cpo
74 } // namespace ranges
75 
76 #endif // _LIBCPP_STD_VER >= 20
77 
78 _LIBCPP_END_NAMESPACE_STD
79 
80 #endif // _LIBCPP___ITERATOR_NEXT_H
81