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// <vector>
10
11// reference at(size_type n); // constexpr since C++20
12
13#include <cassert>
14#include <memory>
15#include <vector>
16
17#include "min_allocator.h"
18#include "test_allocator.h"
19#include "test_macros.h"
20
21#ifndef TEST_HAS_NO_EXCEPTIONS
22# include <stdexcept>
23#endif
24
25template <typename Allocator>
26TEST_CONSTEXPR_CXX20 void test() {
27 using C = std::vector<bool, Allocator>;
28 using reference = typename C::reference;
29 bool a[] = {1, 0, 1, 0, 1};
30 C v(a, a + sizeof(a) / sizeof(a[0]));
31 ASSERT_SAME_TYPE(reference, decltype(v.at(0)));
32 assert(v.at(0) == true);
33 assert(v.at(1) == false);
34 assert(v.at(2) == true);
35 assert(v.at(3) == false);
36 assert(v.at(4) == true);
37 v.at(1) = 1;
38 assert(v.at(1) == true);
39 v.at(3) = 1;
40 assert(v.at(3) == true);
41}
42
43template <typename Allocator>
44void test_exception() {
45#ifndef TEST_HAS_NO_EXCEPTIONS
46 {
47 bool a[] = {1, 0, 1, 1};
48 using C = std::vector<bool, Allocator>;
49 C v(a, a + sizeof(a) / sizeof(a[0]));
50
51 try {
52 TEST_IGNORE_NODISCARD v.at(4);
53 assert(false);
54 } catch (std::out_of_range const&) {
55 // pass
56 } catch (...) {
57 assert(false);
58 }
59
60 try {
61 TEST_IGNORE_NODISCARD v.at(5);
62 assert(false);
63 } catch (std::out_of_range const&) {
64 // pass
65 } catch (...) {
66 assert(false);
67 }
68
69 try {
70 TEST_IGNORE_NODISCARD v.at(6);
71 assert(false);
72 } catch (std::out_of_range const&) {
73 // pass
74 } catch (...) {
75 assert(false);
76 }
77
78 try {
79 using size_type = typename C::size_type;
80 TEST_IGNORE_NODISCARD v.at(static_cast<size_type>(-1));
81 assert(false);
82 } catch (std::out_of_range const&) {
83 // pass
84 } catch (...) {
85 assert(false);
86 }
87 }
88
89 {
90 std::vector<bool, Allocator> v;
91 try {
92 TEST_IGNORE_NODISCARD v.at(0);
93 assert(false);
94 } catch (std::out_of_range const&) {
95 // pass
96 } catch (...) {
97 assert(false);
98 }
99 }
100#endif
101}
102
103TEST_CONSTEXPR_CXX20 bool tests() {
104 test<std::allocator<bool> >();
105 test<min_allocator<bool> >();
106 test<test_allocator<bool> >();
107 return true;
108}
109
110void test_exceptions() {
111 test_exception<std::allocator<bool> >();
112 test_exception<min_allocator<bool> >();
113 test_exception<test_allocator<bool> >();
114}
115
116int main(int, char**) {
117 tests();
118 test_exceptions();
119
120#if TEST_STD_VER >= 20
121 static_assert(tests());
122#endif
123
124 return 0;
125}
126

source code of libcxx/test/std/containers/sequences/vector.bool/at.pass.cpp