C++ Logo

std-proposals

Advanced search

Re: [std-proposals] User defined decay operator

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Thu, 20 Mar 2025 23:20:10 -0400
On Thu, Mar 20, 2025 at 12:16 PM Marcin Jaczewski via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
> Right now the only type that undergoes decaying is C array (aside of
> refs or bit fields).
> Some consider this "bad feature" but for me this is more is "bad
> implementation" of "good feature".
>
> I think that many user defined types could benefit from this functionality.
>
> Proxy objects:
> ```
> std::vector<bool> ff = { false, false };
> for (auto b : ff)
> {
> b = true;
> }
> assert(ff[0] == true);
> ```

I'm confused by this one. Because... it already "works"; it does what
you seem to want.

The problem is that it *shouldn't*.

The result of doing `operator*` on a `vector<bool>` is not a `bool&`;
it is a proxy object that acts like a reference to a bool. But since
we're using `auto` which does not deduce references, `auto b` will
deduce it as the actual proxy object type. So it's an "object", but
that object acts like a reference. You can assign a bool to it, and it
will modify the vector accordingly.

Had this been a `vector<int>`, it wouldn't "work". Which is *actually*
the behavior we want, because that's how it works for iteration over
any non-proxy range. If you want to modify the elements of a container
via ranged-based for, then you should use `auto&&`. If you use values
instead of references, you should not expect them to work.

And I'm uncomfortable with the idea of trying to allow it to invisibly "work".

Received on 2025-03-21 03:20:23