C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Bool casting operator to check if a container not empty

From: Arthur O'Dwyer <arthur.j.odwyer_at_[hidden]>
Date: Wed, 1 Nov 2023 16:59:49 -0400
On Wed, Nov 1, 2023 at 3:09 PM Giuseppe D'Angelo via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> On 01/11/2023 02:45, Hewill Kang via Std-Proposals wrote:
> > Ranges adaptors *do* provide (explicit) operator bool since they all
> > derived from ‘view_interface’.
>
> With this precedent, for better or worse, I'd say that the decision has
> already been taken, and operator bool() should be added to all
> containers. It makes very little sense that
> if (vector)
> doesn't compile, but
> if (views::all(vector))
> does.
>

For the record, I'm personally strongly against this proposal. It's bad
enough that `optional<T>` is truthy; we really don't want `string` and
`span` and so on also gaining truthiness. In a perfect world, we'd simply
*remove* the implicit conversions from all the things that *currently* have
them. (But of course we can't, because Hyrum's Law.)
In particular, as others have pointed out, it would be insane for
    if ("")
to be truthy but
    if (""sv)
to be falsey.

If you want to check something for emptiness, just check .empty().
And if you've got a type that "can be empty" but fails to provide .empty()
as a member function, file a DR! LWG is fixing iota_view
<https://cplusplus.github.io/LWG/issue4001> as we speak, and my own P3016 fixes
std::initializer_list
<https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/p3016r0.html>.
But nota bene, "empty" is not the same thing as "disengaged" is not the
same thing as "null" is not the same thing as "zero-valued." These are
fundamentally distinct concepts, and it's important that they have distinct
names in the C++ standard library.

–Arthur

Received on 2023-11-01 21:00:04