xref: /llvm-project/libcxx/test/std/strings/basic.string/string.access/at.pass.cpp (revision 7149bb70681a91de5d490b4bb0714d9e55a05bcc)
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;
12 //       reference at(size_type pos);
13 
14 #include <string>
15 #include <stdexcept>
16 #include <cassert>
17 
18 #include "min_allocator.h"
19 
20 #include "test_macros.h"
21 
22 template <class S>
23 void
24 test(S s, typename S::size_type pos)
25 {
26     const S& cs = s;
27     if (pos < s.size())
28     {
29         assert(s.at(pos) == s[pos]);
30         assert(cs.at(pos) == cs[pos]);
31     }
32 #ifndef TEST_HAS_NO_EXCEPTIONS
33     else
34     {
35         try
36         {
37             TEST_IGNORE_NODISCARD s.at(pos);
38             assert(false);
39         }
40         catch (std::out_of_range&)
41         {
42             assert(pos >= s.size());
43         }
44         try
45         {
46             TEST_IGNORE_NODISCARD cs.at(pos);
47             assert(false);
48         }
49         catch (std::out_of_range&)
50         {
51             assert(pos >= s.size());
52         }
53     }
54 #endif
55 }
56 
57 int main(int, char**)
58 {
59     {
60     typedef std::string S;
61     test(S(), 0);
62     test(S("123"), 0);
63     test(S("123"), 1);
64     test(S("123"), 2);
65     test(S("123"), 3);
66     }
67 #if TEST_STD_VER >= 11
68     {
69     typedef std::basic_string<char, std::char_traits<char>, min_allocator<char>> S;
70     test(S(), 0);
71     test(S("123"), 0);
72     test(S("123"), 1);
73     test(S("123"), 2);
74     test(S("123"), 3);
75     }
76 #endif
77 
78   return 0;
79 }
80