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> 25 TEST_CONSTEXPR_CXX20 void 26 test(S s, typename S::size_type pos) 27 { 28 const S& cs = s; 29 if (pos < s.size()) 30 { 31 assert(s.at(pos) == s[pos]); 32 assert(cs.at(pos) == cs[pos]); 33 } 34 #ifndef TEST_HAS_NO_EXCEPTIONS 35 else if (!TEST_IS_CONSTANT_EVALUATED) 36 { 37 try 38 { 39 TEST_IGNORE_NODISCARD s.at(pos); 40 assert(false); 41 } 42 catch (std::out_of_range&) 43 { 44 assert(pos >= s.size()); 45 } 46 try 47 { 48 TEST_IGNORE_NODISCARD cs.at(pos); 49 assert(false); 50 } 51 catch (std::out_of_range&) 52 { 53 assert(pos >= s.size()); 54 } 55 } 56 #endif 57 } 58 59 template <class S> 60 TEST_CONSTEXPR_CXX20 void test_string() { 61 test(S(), 0); 62 test(S(MAKE_CSTRING(typename S::value_type, "123")), 0); 63 test(S(MAKE_CSTRING(typename S::value_type, "123")), 1); 64 test(S(MAKE_CSTRING(typename S::value_type, "123")), 2); 65 test(S(MAKE_CSTRING(typename S::value_type, "123")), 3); 66 } 67 68 struct TestCaller { 69 template <class T> 70 TEST_CONSTEXPR_CXX20 void operator()() { 71 test_string<std::basic_string<T> >(); 72 #if TEST_STD_VER >= 11 73 test_string<std::basic_string<T, std::char_traits<T>, min_allocator<T> > >(); 74 #endif 75 } 76 }; 77 78 TEST_CONSTEXPR_CXX20 bool test() { 79 types::for_each(types::character_types(), TestCaller()); 80 81 return true; 82 } 83 84 int main(int, char**) 85 { 86 test(); 87 #if TEST_STD_VER > 17 88 static_assert(test()); 89 #endif 90 91 return 0; 92 } 93