C++ Logo

std-proposals

Advanced search

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

From: Ville Voutilainen <ville.voutilainen_at_[hidden]>
Date: Thu, 2 Nov 2023 17:09:55 +0200
On Thu, 2 Nov 2023 at 16:28, Jason McKesson via Std-Proposals
<std-proposals_at_[hidden]> wrote:
> What kind of generic code are you operating in where you have some
> unknown `T` that could be a pointer, optional, or range, *and* you
> need to know if it is "empty"?
>
> You test a pointer or optional to see if you can dereference it. You
> cannot dereference a range. So what code exactly is going on inside
> this hypothetical `if` statement?

A call to an overload set that deals with ranges or singular values. Thus:

template<class T, class F> void checked_process_it(T&& t)
{
    if (t)
       process_it(std::forward<T>(t));
    else
       nag("hey, don't do that");
}

Then you can do the things in process_it overloads without having to
check that the things given to it are not empty.

> > The point of
> > suggesting that containers could be bool-checked is that a contextual
> > conversion
> > to bool would be that generic check.
>
> Which will not work for arbitrary ranges because `std::ranges::range`
> does not have a bool-check as part of its constraints. So this would
> only be a generic check for containers and maybe views, not all
> ranges.

Perhaps that's why it should then be added to containers, and maybe ranges too.

> So what kind of generic code are you writing where it is OK for it to
> work on views and containers but not for any `range` type? You can't
> backport this into `range`, after all, as this would break a ton of
> code.

I can put it into a refined range concept that has the ability to
check emptiness, though.
And this really sounds like a bug in ranges that could be entertained
to be fixed retroactively,
even if that causes a little breakage. It's quite odd if a generic
view that can be as lazy as imaginable
can provide an empty() but a generic range can't.

Received on 2023-11-02 15:10:10