C++ Logo

std-proposals

Advanced search

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

From: Charles R Hogg <charles.r.hogg_at_[hidden]>
Date: Sun, 16 Nov 2025 12:15:23 -0500
One potential use case for this would be a quantities-and-units library
that supports vectors and matrices of heterogeneous quantities. In those
cases, the *return type* can be different for different indices! The
`std::cw<N>` notation for indices could be a nice and ergonomic syntax.
For example, in a 6D vector representing an element of the tangent space of
SE(3) (very useful as a 3D pose in robotics applications), `v[std::cw<0>]`
might return a `Quantity<Radians, double>`, while `v[std::cw<3>>]` might
return a `Quantity<Meters, double>`.

On Sun, Nov 16, 2025 at 10:43 AM Hewill Kang via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> The example would be:
> ```
> std::array<int, 5> a;
> a[std::cw<42>]; // compile-time error X
>
> std::bitset<5> b;
> b[std::cw<42>]; // compile-time error X
>
> int arr[] = {1, 2, 3, 4, 5, 6};
> std::mdspan m(arr, std::cw<2>, 3);
> m[std::cw<42>, 0]; // compile-time error X
>
> std::simd::vector<int> s;
> s[std::cw<42>]; // compile-time error X
>
> std::vector<int> v;
> v[std::cw<42>]; // no cw-overload, so run-time error X
> ```
>
> I think this might be a bit far-fetched, because it changes the
> long-standing expected use case of operator[]. More precisely, it provides
> a more complex overload for operator[]. I don't know if it's worth it.
>
> But for `mdspan`, this probably might be feasible because its
> `operator[]` is already a variadic template, which means it can take
> `std::cw<42>`, we just didn't perform a static inspection.
>
>
>
> Hewill Kang <hewillk_at_[hidden]> 於 2025年11月16日 週日 上午2:52寫道:
>
>> 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-16 17:15:40