C++ Logo


Advanced search

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

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Tue, 9 Aug 2022 15:29:14 -0400
On Tue, Aug 9, 2022 at 1:52 PM Guillaume Racicot via Std-Proposals
<std-proposals_at_[hidden]> wrote:
> Hello C++,
> I had an idea to make the language more consistent and probably easier
> to teach. It would be to allow explicit types to be destructured
> instead of only CV qualified auto.
> Here's a syntax example of this feature:
> std::tuple<int, float> [a, b] = std::make_tuple(1, 2.4f);
> Notice here that an explicit type `std::tuple<int, float>` is being
> destructured instead of enforcing `auto`.
> My reason for this is that the language already has some surprising
> behavior surrounding structured binding already. Consider this code:
> int i1 = 0, i2 = 0;
> auto [a, b] = std::tie(i1, i2);
> // even though `auto` is specified, `a` and `b` are still references
> i1 = 1;
> assert(a == 1); // passes

That's not too surprising, as this is what you asked for when you used

> Structured bindings are, as far as I know, the *only* place where C++
> artificially
> enforces `auto` where an explicit type could technically be written,
> and I don't think there is a particularly good reason for that.

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.

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`.

Received on 2022-08-09 19:29:21