บิตรายวัน (e) ของ C++ #229 คอนเทนเนอร์อาร์เรย์ที่มีขนาดคงที่: std::array

std::array เป็นคอนเทนเนอร์ที่แสดงถึงอาร์เรย์ที่มีขนาดคงที่ นอกจากอินเทอร์เฟซช่วงแล้ว std::array ยังหลีกเลี่ยงการสลายโดยนัยในตัวชี้ (เช่น int[3] เข้าสู่ int*)

ยิ่งไปกว่านั้น std::array ยังไม่มีตัวสร้างที่ชัดเจน ทำให้สามารถรักษาคุณสมบัติที่สามารถคัดลอกได้เล็กน้อยของข้อมูลพื้นฐาน

#include <array>
#include <algorithm>
#include <functional>

void fun(int,int,int,int,int) {}
struct A { A(int,int,int,int,int) {} };


std::array<int,5> data{1,2,3,4,5};

// Models contiguous range
std::ranges::sort(data, std::greater<>{});
// data == {5,4,3,2,1}

// Models tupple-like (C++11)
int x = std::get<2>(data);
// x == 4
size_t sz = std::tuple_size<decltype(data)>{};
// sz == 5

// Since C++17:
auto [a,b,c,d,e] = data;
// a == 5, b == 4, c == 3, d == 2, e == 1

// Since C++23:
// Construct A with the elements of data
A m = std::make_from_tuple<A>(data);
// Call fun with the elements of data
std::apply(fun, data);

เปิดตัวอย่างใน Compiler Explorer