C++ Logo

std-proposals

Advanced search

Re: [std-proposals] compile-time safety operator[]?

From: Sebastian Wittmeier <wittmeier_at_[hidden]>
Date: Mon, 17 Nov 2025 09:06:46 +0100
One disadvantage of the std::cw parameter of [] is that one cannot distinguish at the call site, whether a given index is checked at compile-time or not.   -----Ursprüngliche Nachricht----- Von:Hewill Kang via Std-Proposals <std-proposals_at_[hidden]> Gesendet:Sa 15.11.2025 19:52 Betreff:[std-proposals] compile-time safety operator[]? An:std-proposals <std-proposals_at_[hidden]>; CC:Hewill Kang <hewillk_at_[hidden]>; Hi all, C++26 introduced `std::cw` to represent compile-time constants, a stronger alternative to integral_constant, see https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2025/p2781r9.html And we know that the C++26 Standard library has hardened a large number of `operator[]`s, see https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2025/p3471r4.html. I'm wondering if combining `cw` and `operator[]` is the right direction. For example, we could provide `cw` overloads for `operator[]` of containers that have size information at compile time, such as `array<T, N>`, `span<T, N>`, `inplace_vector<T, N>`, and it directly rejects out-of-bounds access via Mandates: ``` constexpr reference operator[](integral-constant-like auto idx) const; Mandates: idx < size() is true. Effects: Equivalent to: return operator[decltype(idx)::value]; ``` This seems to allow us to check for out-of-bounds issues at compile time, avoiding runtime Hardened preconditions. Is this reasonable? Hewill -- Std-Proposals mailing list Std-Proposals_at_[hidden] https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2025-11-17 08:20:42