1 //===----------------------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 // UNSUPPORTED: c++03, c++11, c++14, c++17
10
11 // constexpr auto size() requires sized_range<R>
12 // constexpr auto size() const requires sized_range<const R>
13
14 #include <ranges>
15
16 #include <array>
17 #include <cassert>
18 #include <concepts>
19
20 #include "test_iterators.h"
21 #include "test_macros.h"
22
23 template <class T>
24 concept HasSize = requires (T t) {
25 t.size();
26 };
27
test()28 constexpr bool test()
29 {
30 {
31 struct SubtractableIters {
32 forward_iterator<int*> begin();
33 sized_sentinel<forward_iterator<int*>> end();
34 };
35 using OwningView = std::ranges::owning_view<SubtractableIters>;
36 static_assert(std::ranges::sized_range<OwningView&>);
37 static_assert(!std::ranges::range<const OwningView&>); // no begin/end
38 static_assert(HasSize<OwningView&>);
39 static_assert(HasSize<OwningView&&>);
40 static_assert(!HasSize<const OwningView&>);
41 static_assert(!HasSize<const OwningView&&>);
42 }
43 {
44 struct NoSize {
45 bidirectional_iterator<int*> begin();
46 bidirectional_iterator<int*> end();
47 };
48 using OwningView = std::ranges::owning_view<NoSize>;
49 static_assert(!HasSize<OwningView&>);
50 static_assert(!HasSize<OwningView&&>);
51 static_assert(!HasSize<const OwningView&>);
52 static_assert(!HasSize<const OwningView&&>);
53 }
54 {
55 struct SizeMember {
56 bidirectional_iterator<int*> begin();
57 bidirectional_iterator<int*> end();
58 int size() const;
59 };
60 using OwningView = std::ranges::owning_view<SizeMember>;
61 static_assert(std::ranges::sized_range<OwningView&>);
62 static_assert(!std::ranges::range<const OwningView&>); // no begin/end
63 static_assert(HasSize<OwningView&>);
64 static_assert(HasSize<OwningView&&>);
65 static_assert(!HasSize<const OwningView&>); // not a range, therefore no size()
66 static_assert(!HasSize<const OwningView&&>);
67 }
68 {
69 // Test an empty view.
70 int a[] = {1};
71 auto ov = std::ranges::owning_view(std::ranges::subrange(a, a));
72 assert(ov.size() == 0);
73 assert(std::as_const(ov).size() == 0);
74 }
75 {
76 // Test a non-empty view.
77 int a[] = {1};
78 auto ov = std::ranges::owning_view(std::ranges::subrange(a, a+1));
79 assert(ov.size() == 1);
80 assert(std::as_const(ov).size() == 1);
81 }
82 {
83 // Test a non-view.
84 std::array<int, 2> a = {1, 2};
85 auto ov = std::ranges::owning_view(std::move(a));
86 assert(ov.size() == 2);
87 assert(std::as_const(ov).size() == 2);
88 }
89 return true;
90 }
91
main(int,char **)92 int main(int, char**) {
93 test();
94 static_assert(test());
95
96 return 0;
97 }
98