[libcxx-commits] [libcxx] [libc++] Optimize {std, ranges}::distance for segmented iterators (PR #133612)

Louis Dionne via libcxx-commits libcxx-commits at lists.llvm.org
Tue Jun 24 10:31:18 PDT 2025


================
@@ -10,41 +10,82 @@
 #ifndef _LIBCPP___ITERATOR_DISTANCE_H
 #define _LIBCPP___ITERATOR_DISTANCE_H
 
+#include <__algorithm/for_each_segment.h>
 #include <__config>
 #include <__iterator/concepts.h>
 #include <__iterator/incrementable_traits.h>
 #include <__iterator/iterator_traits.h>
+#include <__iterator/segmented_iterator.h>
 #include <__ranges/access.h>
 #include <__ranges/concepts.h>
 #include <__ranges/size.h>
 #include <__type_traits/decay.h>
+#include <__type_traits/enable_if.h>
 #include <__type_traits/remove_cvref.h>
+#include <__utility/move.h>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #  pragma GCC system_header
 #endif
 
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
 _LIBCPP_BEGIN_NAMESPACE_STD
 
-template <class _InputIter>
-inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX17 typename iterator_traits<_InputIter>::difference_type
-__distance(_InputIter __first, _InputIter __last, input_iterator_tag) {
-  typename iterator_traits<_InputIter>::difference_type __r(0);
+#if _LIBCPP_STD_VER >= 20
+template <class _Iter>
+using __iter_distance_t _LIBCPP_NODEBUG = std::iter_difference_t<_Iter>;
----------------
ldionne wrote:

We already have `__iter_diff_t` in `iterator_traits.h`. It doesn't do exactly what you want, but I think we should make it do what you need instead of introducing a new thing that's essentially identical.

Basically, we should try re-defining `__iter_diff_t` in `iterator_traits.h` as:

```c++
#if _LIBCPP_STD_VER >= 20
template <class _Iter>
using __iter_diff_t _LIBCPP_NODEBUG = std::iter_difference_t<_Iter>;
#else
template <class _Iter>
using __iter_diff_t _LIBCPP_NODEBUG = typename iterator_traits<_Iter>::difference_type;
#endif
```

And if that's not possible for some reason, it would be interesting to understand why.

https://github.com/llvm/llvm-project/pull/133612


More information about the libcxx-commits mailing list