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:40:02 +0200
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

Received on 2023-10-19 10:40:14