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 // <array> 10 11 // reference operator[] (size_type) 12 // const_reference operator[] (size_type); // constexpr in C++14 13 // reference at (size_type) 14 // const_reference at (size_type); // constexpr in C++14 15 16 #include <array> 17 #include <cassert> 18 19 #include "test_macros.h" 20 21 // std::array is explicitly allowed to be initialized with A a = { init-list };. 22 // Disable the missing braces warning for this reason. 23 #include "disable_missing_braces_warning.h" 24 25 #if TEST_STD_VER > 14 26 constexpr bool check_idx( size_t idx, double val ) 27 { 28 std::array<double, 3> arr = {1, 2, 3.5}; 29 return arr[idx] == val; 30 } 31 #endif 32 33 int main(int, char**) 34 { 35 { 36 typedef double T; 37 typedef std::array<T, 3> C; 38 C c = {1, 2, 3.5}; 39 C::reference r1 = c[0]; 40 assert(r1 == 1); 41 r1 = 5.5; 42 assert(c.front() == 5.5); 43 44 C::reference r2 = c[2]; 45 assert(r2 == 3.5); 46 r2 = 7.5; 47 assert(c.back() == 7.5); 48 } 49 { 50 typedef double T; 51 typedef std::array<T, 3> C; 52 const C c = {1, 2, 3.5}; 53 C::const_reference r1 = c[0]; 54 assert(r1 == 1); 55 C::const_reference r2 = c[2]; 56 assert(r2 == 3.5); 57 } 58 { // Test operator[] "works" on zero sized arrays 59 typedef double T; 60 typedef std::array<T, 0> C; 61 C c = {}; 62 C const& cc = c; 63 static_assert((std::is_same<decltype(c[0]), T &>::value), ""); 64 static_assert((std::is_same<decltype(cc[0]), const T &>::value), ""); 65 if (c.size() > (0)) { // always false 66 C::reference r1 = c[0]; 67 C::const_reference r2 = cc[0]; 68 ((void)r1); 69 ((void)r2); 70 } 71 } 72 { // Test operator[] "works" on zero sized arrays 73 typedef double T; 74 typedef std::array<const T, 0> C; 75 C c = {{}}; 76 C const& cc = c; 77 static_assert((std::is_same<decltype(c[0]), const T &>::value), ""); 78 static_assert((std::is_same<decltype(cc[0]), const T &>::value), ""); 79 if (c.size() > (0)) { // always false 80 C::reference r1 = c[0]; 81 C::const_reference r2 = cc[0]; 82 ((void)r1); 83 ((void)r2); 84 } 85 } 86 #if TEST_STD_VER > 11 87 { 88 typedef double T; 89 typedef std::array<T, 3> C; 90 constexpr C c = {1, 2, 3.5}; 91 92 constexpr T t1 = c[0]; 93 static_assert (t1 == 1, ""); 94 95 constexpr T t2 = c[2]; 96 static_assert (t2 == 3.5, ""); 97 } 98 #endif 99 100 #if TEST_STD_VER > 14 101 { 102 static_assert (check_idx(0, 1), ""); 103 static_assert (check_idx(1, 2), ""); 104 static_assert (check_idx(2, 3.5), ""); 105 } 106 #endif 107 108 return 0; 109 } 110