C++ Logo


Advanced search

Re: [std-proposals] C-style array specialization for std::get

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Tue, 1 Mar 2022 10:00:57 -0500
On Mon, Feb 28, 2022 at 2:04 PM Nikolay Mihaylov via Std-Proposals
<std-proposals_at_[hidden]> wrote:
> no need to deduce the size, I would do it like this:
> #include <cstdint>
> template<std::size_t IX, typename T>
> auto const &get(T const *a){
> return a[IX];
> }
> int main(){
> int x[100] = { 0, 1, 2, 3 };
> return get<3>(x);
> }

That makes it possible to use a random pointer with `std::get`. The
point of this feature is that you can provide a compile-time index for
accessing a C-style array (and compile-time bounds checking). By
deducing the size, you prevent people from just passing a pointer,
which is *good* because that's not what the feature is for.

If you have a compile-time index, and a compile-time sized array,
there is zero reason to allow out-of-bounds accesses. And if you have
a runtime-sized array... you shouldn't be using `std::get` for it. The
`std::get` interface isn't for runtime-sized things.

Received on 2022-03-01 15:01:03