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// <string>
10
11// const_reference at(size_type pos) const; // constexpr since C++20
12// reference at(size_type pos); // constexpr since C++20
13
14#include <string>
15#include <stdexcept>
16#include <cassert>
17
18#include "min_allocator.h"
19
20#include "make_string.h"
21#include "test_macros.h"
22#include "type_algorithms.h"
23
24template <class S>
25TEST_CONSTEXPR_CXX20 void test(S s, typename S::size_type pos) {
26 const S& cs = s;
27 if (pos < s.size()) {
28 assert(s.at(pos) == s[pos]);
29 assert(cs.at(pos) == cs[pos]);
30 }
31#ifndef TEST_HAS_NO_EXCEPTIONS
32 else if (!TEST_IS_CONSTANT_EVALUATED) {
33 try {
34 TEST_IGNORE_NODISCARD s.at(pos);
35 assert(false);
36 } catch (std::out_of_range&) {
37 assert(pos >= s.size());
38 }
39 try {
40 TEST_IGNORE_NODISCARD cs.at(pos);
41 assert(false);
42 } catch (std::out_of_range&) {
43 assert(pos >= s.size());
44 }
45 }
46#endif
47}
48
49template <class S>
50TEST_CONSTEXPR_CXX20 void test_string() {
51 test(S(), 0);
52 test(S(MAKE_CSTRING(typename S::value_type, "123")), 0);
53 test(S(MAKE_CSTRING(typename S::value_type, "123")), 1);
54 test(S(MAKE_CSTRING(typename S::value_type, "123")), 2);
55 test(S(MAKE_CSTRING(typename S::value_type, "123")), 3);
56}
57
58struct TestCaller {
59 template <class T>
60 TEST_CONSTEXPR_CXX20 void operator()() {
61 test_string<std::basic_string<T> >();
62#if TEST_STD_VER >= 11
63 test_string<std::basic_string<T, std::char_traits<T>, min_allocator<T> > >();
64#endif
65 }
66};
67
68TEST_CONSTEXPR_CXX20 bool test() {
69 types::for_each(types::character_types(), TestCaller());
70
71 return true;
72}
73
74int main(int, char**) {
75 test();
76#if TEST_STD_VER > 17
77 static_assert(test());
78#endif
79
80 return 0;
81}
82

source code of libcxx/test/std/strings/basic.string/string.access/at.pass.cpp