xref: /llvm-project/libcxx/test/std/strings/basic.string/string.access/at.pass.cpp (revision a40bada91aeda276a772acfbcae6e8de26755a11)
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 
24 template <class S>
test(S s,typename S::size_type pos)25 TEST_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 
49 template <class S>
test_string()50 TEST_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 
58 struct TestCaller {
59   template <class T>
operator ()TestCaller60   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 
test()68 TEST_CONSTEXPR_CXX20 bool test() {
69   types::for_each(types::character_types(), TestCaller());
70 
71   return true;
72 }
73 
main(int,char **)74 int main(int, char**) {
75   test();
76 #if TEST_STD_VER > 17
77   static_assert(test());
78 #endif
79 
80   return 0;
81 }
82