C++ Logo

std-proposals

Advanced search

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

From: Guillaume Racicot <gracicot42_at_[hidden]>
Date: Tue, 9 Aug 2022 13:51:45 -0400
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

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. The
language also
allows CV qualifiers, but those are also applied to the unnamed
object, not the bindings.

Rationale and opinions aside, I was first wondering if there were
obvious problems that would make this syntax unimplementable or
ambiguous. I am willing to write the proposal for it and learn the
necessary steps to make it advance.

Thank you for your time, and I hope to learn much during this process!
Guillaume Racicot

Received on 2022-08-09 17:51:56