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 decltype(auto) operator[](difference_type n) const
12// requires random_access_range<Base>
13
14#include <cassert>
15#include <ranges>
16#include <tuple>
17
18#include "test_iterators.h"
19
20template <class T, class U>
21concept CanSubscript = requires(T t, U u) { t[u]; };
22
23template <class BaseRange>
24using ElemIter = std::ranges::iterator_t<std::ranges::elements_view<BaseRange, 0>>;
25
26using RandomAccessRange = std::ranges::subrange<std::tuple<int>*>;
27static_assert(std::ranges::random_access_range<RandomAccessRange>);
28
29static_assert(CanSubscript<ElemIter<RandomAccessRange>, int>);
30
31using BidiRange = std::ranges::subrange<bidirectional_iterator<std::tuple<int>*>>;
32static_assert(!std::ranges::random_access_range<BidiRange>);
33
34static_assert(!CanSubscript<ElemIter<BidiRange>, int>);
35
36constexpr bool test() {
37 {
38 // reference
39 std::tuple<int> ts[] = {{1}, {2}, {3}, {4}};
40 auto ev = ts | std::views::elements<0>;
41 auto it = ev.begin();
42
43 assert(&it[0] == &*it);
44 assert(&it[2] == &*(it + 2));
45
46 static_assert(std::is_same_v<decltype(it[2]), int&>);
47 }
48
49 {
50 // value
51 auto ev = std::views::iota(0, 5) | std::views::transform([](int i) { return std::tuple<int>{i}; }) |
52 std::views::elements<0>;
53 auto it = ev.begin();
54 assert(it[0] == *it);
55 assert(it[2] == *(it + 2));
56 assert(it[4] == *(it + 4));
57
58 static_assert(std::is_same_v<decltype(it[2]), int>);
59 }
60
61 return true;
62}
63
64int main(int, char**) {
65 test();
66 static_assert(test());
67
68 return 0;
69}
70

source code of libcxx/test/std/ranges/range.adaptors/range.elements/iterator/subscript.pass.cpp