C++ Logo

std-proposals

Advanced search

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

From: Marcin Jaczewski <marcinjaczewski86_at_[hidden]>
Date: Thu, 19 Oct 2023 12:52:22 +0200
czw., 19 paź 2023 o 12:47 Oleksandr Koval
<oleksandr.koval.dev_at_[hidden]> napisał(a):
>
> The code like
> ```
> if (vect) foo(vect[0]);
> ```
> doesn't make sense for all containers, e.g. for unordered_map so this `operator bool` proposal is not generic.
>

This was only to show this is similar to a pointer, not how it should
be used everywhere.
Usually you use more than the first element.

> My personal mental model about `operator bool` is a check when an object doesn't exist or it's not usable (in a normal way) or, if it's a wrapper, it wraps nothing.
>

At least for me it is "have data" and it fits nicely with all containers.

> On Thu, Oct 19, 2023 at 1:40 PM Marcin Jaczewski via Std-Proposals <std-proposals_at_[hidden]> wrote:
>>
>> czw., 19 paź 2023 o 12:27 Bo Persson via Std-Proposals
>> <std-proposals_at_[hidden]> napisał(a):
>> >
>> > On 2023-10-19 at 12:05, Alex Rozenman via Std-Proposals wrote:
>> > > In many cases, when it is needed to check if a container not empty,
>> > > "size()" or "empty()" functions are used:
>> > >
>> > > if (vect.size() != 0) {
>> > >
>> > > // vector is not empty
>> > >
>> > > }
>> > >
>> > > if (!vect.empty()) {
>> > >
>> > > // vector is not empty
>> > >
>> > > }
>> > >
>> > >
>> > > It seems that both variants are not expressive enough, so an explicit
>> > > function may be required, like:
>> > >
>> > > if (vect.not_empty()) {
>> > >
>> > > // vector is not empty
>> > >
>> > > }
>> > >
>> >
>> > Could you live with if(not vect.empty()) ?
>> >
>> > If so, that already works.
>> >
>> >
>> >
>> > >
>> > > In this message I would like to suggest to use of a bool casting
>> > > operator as the most clean form of this function:
>> > >
>> > > if (vect) {
>> > >
>> > > // vector is not empty
>> > >
>> > > }
>> > >
>> >
>> > It might be "clean", but I read this as vect is a pointer that might be
>> > null. Not obvious how this is an improvement.
>>
>> ```
>> if (vect) foo(vect[0]);
>> if (ptr) foo(ptr[0]);
>> ```
>> Both are equivalent.
>> At least in my code base I use the `bool` operator like this.
>>
>> >
>> >
>> >
>> >
>> > --
>> > Std-Proposals mailing list
>> > Std-Proposals_at_[hidden]
>> > https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>> --
>> Std-Proposals mailing list
>> Std-Proposals_at_[hidden]
>> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>
>
>
> --
> Regards,
> Oleksandr Koval.

Received on 2023-10-19 10:52:35