libstdc++: Implement LWG 3392 for std::ranges::distance
authorJonathan Wakely <jwakely@redhat.com>
Tue, 1 Jun 2021 13:22:38 +0000 (14:22 +0100)
committerJonathan Wakely <jwakely@redhat.com>
Fri, 1 Oct 2021 19:36:54 +0000 (20:36 +0100)
libstdc++-v3/ChangeLog:

* include/bits/ranges_base.h (ranges::distance): Split overload
into two (LWG 3392).
* testsuite/24_iterators/range_operations/lwg3392.cc: New test.

libstdc++-v3/include/bits/ranges_base.h
libstdc++-v3/testsuite/24_iterators/range_operations/lwg3392.cc [new file with mode: 0644]

index d6166ab..01d0c35 100644 (file)
@@ -787,22 +787,25 @@ namespace ranges
   struct __distance_fn final
   {
     template<input_or_output_iterator _It, sentinel_for<_It> _Sent>
-      [[nodiscard]]
+      requires (!sized_sentinel_for<_Sent, _It>)
       constexpr iter_difference_t<_It>
-      operator()(_It __first, _Sent __last) const
+      operator()[[nodiscard]](_It __first, _Sent __last) const
       {
-       if constexpr (sized_sentinel_for<_Sent, _It>)
-         return __last - __first;
-       else
+       iter_difference_t<_It> __n = 0;
+       while (__first != __last)
          {
-           iter_difference_t<_It> __n = 0;
-           while (__first != __last)
-             {
-               ++__first;
-               ++__n;
-             }
-           return __n;
+           ++__first;
+           ++__n;
          }
+       return __n;
+      }
+
+    template<input_or_output_iterator _It, sized_sentinel_for<_It> _Sent>
+      [[nodiscard]]
+      constexpr iter_difference_t<_It>
+      operator()(const _It& __first, const _Sent& __last) const
+      {
+       return __last - __first;
       }
 
     template<range _Range>
diff --git a/libstdc++-v3/testsuite/24_iterators/range_operations/lwg3392.cc b/libstdc++-v3/testsuite/24_iterators/range_operations/lwg3392.cc
new file mode 100644 (file)
index 0000000..3278035
--- /dev/null
@@ -0,0 +1,30 @@
+// { dg-options "-std=gnu++20" }
+// { dg-do compile { target c++20 } }
+
+#include <iterator>
+
+struct movable_iterator
+{
+  using difference_type = long;
+
+  movable_iterator() = default;
+  movable_iterator(movable_iterator&&) = default;
+  movable_iterator& operator=(movable_iterator&&) = default;
+
+  int operator*() const { return 1; }
+
+  movable_iterator& operator++() { return *this; }
+  void operator++(int) { }
+
+  bool operator==(const movable_iterator&) const = default;
+};
+
+using namespace std;
+
+constexpr counted_iterator<movable_iterator> it({}, 3);
+
+static_assert( sized_sentinel_for<std::default_sentinel_t, counted_iterator<movable_iterator>> );
+// LWG 3392
+// ranges::distance() cannot be used on a move-only iterator
+// with a sized sentinel
+static_assert( ranges::distance(it, default_sentinel) == 3 );