C++ Logo


Advanced search

Re: [std-proposals] Allow explicit types for destructured objects in structured bindings

From: Guillaume Racicot <gracicot42_at_[hidden]>
Date: Tue, 9 Aug 2022 16:56:48 -0400
On Tue, Aug 9, 2022 at 3:29 PM Jason McKesson via Std-Proposals
<std-proposals_at_[hidden]> wrote:
> That's not too surprising, as this is what you asked for when you used
> `std::tie`.

In this example it is not, but in generic code it can definitely be a
footgun, since it may not be obvious at first glance. It may not be as
evident as it seems to be, especially for beginners that still don't
know the deduced type by `auto` is actually the type of the unnamed,
decomposed object, not the bindings.

> There is a good reason: parsing.
> "auto [" was, pre-strucutured binding, nonsense. `auto` is a
> placeholder type; array syntax could not be applied to them (unlike
> pointer syntax). Since the syntax was unused, the standard could give
> it meaning.
> "actual_typename [" has a meaning. You are naming an array of
> `actual_typename`. If you are able to use this as a structured binding
> declaration, the language/compiler now has to resolve an ambiguity.
> I don't know how difficult this ambiguity is to resolve.

Hmm, I wonder how ambiguous it really is? You cannot declare anything
`actual_type [` that is not explicitly a type declaration (eg. an
alias declaration) and GCC seem to always diagnose this syntax as
"structured binding declaration cannot have type 'actual_type'"

Here's one example:

    struct S { int a; };
    constexpr int N = 9;
    int main()
        S[N] = S{};


The only place I can see this as ambiguous is in function parameters
since only there you can declare an unnamed array. And even there,
`auto` doesn't help resolve that ambiguity since a function receiving
`auto[N]` where `N` is a compile time constant is actually allowed.

> Personally, I don't really see the point of this feature. The types
> that really matter are the components of the decomposed object, not
> the decomposed object itself. If you want to list those types, you can
> specify them to `make_typle`.

Hmm, maybe there is not much motivation, but I think it would remove
an inconsistency we have in the language, as well as making some code
more readable. This is enough of a motivation for me to at least try.
You may care about the type of the decomposed object for teaching
though, as writing the type explicitly would help construct the
"right" mental model about structured bindings. `auto` and its CV-ref
qualifiers apply to the decomposed object. That in itself can be
confusing if you cannot ever see this type explicitly written.

> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2022-08-09 20:57:00