C++ Logo


Advanced search

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

From: Lénárd Szolnoki <cpp_at_[hidden]>
Date: Mon, 28 Feb 2022 19:08:05 +0000

On Mon, 28 Feb 2022 17:47:16 +0100
Paolo Di Giglio via Std-Proposals <std-proposals_at_[hidden]>

> I'd like to propose a specialization of function template std::get for
> C-style arrays. A simple two-liner would provide compile-time catching
> of out-of-bound array accesses (please note we already have this check
> for the std::array specialization):
> template <std::size_t Idx, typename T, std::size_t N>
> constexpr T& get(T (&arr)[N]) noexcept
> {
> static_assert(Idx < N, "Index out of bounds");
> return arr[Idx];
> }

This is a good idea, there is little reason for C arrays to not have
std::get, especially that std::array has it.

> As far as I know, it's not possible to pass a C-style array by value
> to a function nor to return one from a function. So I think there's
> no need for a r-value reference overload.

It's still possible to produce array rvalues, even prvalues. `std::get`
is specialized for std::array rvalues, so C style arrays should be too.

Also if `expr` is a C array rvalue then `expr[idx]` already produces
xvalue, so in a sense `std::get` would mimic the built-in behavior.

Weirdly enough if `expr` is a std::array rvalue then `expr[idx]` is
still an lvalue, but IMO that's more of an oversight of the
`std::array` implementation.

Here is a godbolt link to play around, looks like MSVC disagrees with
`expr[idx]` being an xvalue when `expr` is a C array rvalue:


> Thanks in advance for your feedbacks.

Lénárd Szolnoki

Received on 2022-02-28 19:08:14