2 //===----------------------------------------------------------------------===//
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
8 //===----------------------------------------------------------------------===//
10 #ifndef _LIBCPP___ITERATOR_PREV_H
11 #define _LIBCPP___ITERATOR_PREV_H
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 #include <__utility/move.h>
22 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
23 # pragma GCC system_header
27 #include <__undef_macros>
29 _LIBCPP_BEGIN_NAMESPACE_STD
31 template <class _InputIter
, __enable_if_t
<__has_input_iterator_category
<_InputIter
>::value
, int> = 0>
32 [[__nodiscard__
]] inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX17 _InputIter
33 prev(_InputIter __x
, typename iterator_traits
<_InputIter
>::difference_type __n
) {
34 // Calling `advance` with a negative value on a non-bidirectional iterator is a no-op in the current implementation.
35 // Note that this check duplicates the similar check in `std::advance`.
36 _LIBCPP_ASSERT_PEDANTIC(__n
<= 0 || __has_bidirectional_iterator_category
<_InputIter
>::value
,
37 "Attempt to prev(it, n) with a positive n on a non-bidirectional iterator");
38 std::advance(__x
, -__n
);
43 // It is unclear what the implications of "BidirectionalIterator" in the standard are.
44 // However, calling std::prev(non-bidi-iterator) is obviously an error and we should catch it at compile time.
45 template <class _InputIter
, __enable_if_t
<__has_input_iterator_category
<_InputIter
>::value
, int> = 0>
46 [[__nodiscard__
]] _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX17 _InputIter
prev(_InputIter __it
) {
47 static_assert(__has_bidirectional_iterator_category
<_InputIter
>::value
,
48 "Attempt to prev(it) with a non-bidirectional iterator");
49 return std::prev(std::move(__it
), 1);
52 #if _LIBCPP_STD_VER >= 20
54 // [range.iter.op.prev]
58 template <bidirectional_iterator _Ip
>
59 [[nodiscard
]] _LIBCPP_HIDE_FROM_ABI
constexpr _Ip
operator()(_Ip __x
) const {
64 template <bidirectional_iterator _Ip
>
65 [[nodiscard
]] _LIBCPP_HIDE_FROM_ABI
constexpr _Ip
operator()(_Ip __x
, iter_difference_t
<_Ip
> __n
) const {
66 ranges::advance(__x
, -__n
);
70 template <bidirectional_iterator _Ip
>
71 [[nodiscard
]] _LIBCPP_HIDE_FROM_ABI
constexpr _Ip
72 operator()(_Ip __x
, iter_difference_t
<_Ip
> __n
, _Ip __bound_iter
) const {
73 ranges::advance(__x
, -__n
, __bound_iter
);
78 inline namespace __cpo
{
79 inline constexpr auto prev
= __prev
{};
83 #endif // _LIBCPP_STD_VER >= 20
85 _LIBCPP_END_NAMESPACE_STD
89 #endif // _LIBCPP___ITERATOR_PREV_H