C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Fwd: destructurable std::integer_sequence

From: Arthur O'Dwyer <arthur.j.odwyer_at_[hidden]>
Date: Sat, 30 Nov 2024 22:37:02 -0500
On Sat, Nov 30, 2024 at 9:16 AM Desmond Gold via Std-Proposals <
std-proposals_at_[hidden]> wrote:

>
> After P1061R10 <https://wg21.link/P1061R10> has been approved for C++26,
> it's now time to let std::integer_sequence be a destructurable type for
> improved usability while still remain its niche
>
> auto [...Is] = std::make_index_sequence<N>();
>
> This addition helps simplify metaprogramming implementations that rely on
> std::integer_sequence.
>

Sounds good to me!
As you've noticed from the replies: "use pack-indexing into a tuple simply
to create the same tuple again" is not a good motivating example.
Perhaps "reverse the tuple" would be more motivating:
https://godbolt.org/z/oPqvMsq9j

BEFORE
template<class... Ts, size_t N = sizeof...(Ts)>
auto reverse_tuple(std::tuple<Ts...> tup) {
return [&]<size_t... Is>(std::index_sequence<Is...>) {
return std::make_tuple(std::get<N - Is - 1>(tup)...);
}(std::make_index_sequence<N>());
}
AFTER
template<class... Ts, size_t N = sizeof...(Ts)>
auto reverse_tuple(std::tuple<Ts...> tup) {
constexpr auto [...Is] = std::make_index_sequence<N>();
return std::make_tuple(std::get<N - Is - 1>(tup)...);
}

However, before this would actually work, you'd also need to propose
`constexpr` structured bindings! Somehow this has failed to work for the
past 9 years.
https://stackoverflow.com/questions/41622896/why-cant-decomposition-declarations-be-constexpr
...Ah, but P2686 constexpr structured bindings
<https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2024/p2686r4.pdf> (Jabot,
Bi) was finally moved to Ready
<https://github.com/cplusplus/papers/issues/1351> in Wroclaw this past
month. Excellent.

There are two options in making these destructurable sequences possible:
> 1.) destructured into individual std::integral_constant:
> 2.) destructured into constant integers
>

The latter, of course.

Basically I think this is a really good idea for a proposal and you should
do it.
I confirm that it can be implemented pretty easily.

constexpr auto [...Is] = std::make_index_sequence<N>();
>
> However, there is one problem. What if the integer sequence is empty? I
> don't know if P1061R10 permits empty structured binding packs from an
> object of zero tuple size.
>

It does. <https://godbolt.org/z/5Pz874ann> Clang trunk already supports
zero-sized bindings as an extension (with a warning), as shown in that
Godbolt link. GCC doesn't yet; but I bet that when GCC starts supporting
P1061 it'll backport zero-sized bindings to all language modes with a
warning (just like Clang) because why not.

–Arthur

Received on 2024-12-01 03:37:20