[LLVMdev] [RFC] Add empty() method to iterator_range.

David Blaikie dblaikie at gmail.com
Thu Mar 20 08:15:26 PDT 2014


On Wed, Mar 19, 2014 at 11:13 AM, Lang Hames <lhames at gmail.com> wrote:
> Hi all,
>
> As RFCs go this is short and sweet - I think it would be nice to add an
> empty method to iterator_range. Something like:
>
> bool empty() const { return begin() != end(); }
>
> My motivation is to make the 'if' test at the start of this common pattern
> tidier:
>
> if (!collection.empty())
>   // initialization...
> for (auto& c : collection)
>   // do something for each c.
>
> which I think that is preferable to:
>
> if (collection.begin() != collection.end())
>   // initialization...
> // for each...
>
> The empty method is just a single iterator comparison, so it should be valid
> and cheap for any underlying iterator type.

For this reason I'd personally consider writing this as a free
function over ranges:

template<typename T>
bool is_empty(T t) { return begin(t) == end(t); }

or the like.

Why bother reimplementing empty in every range/container (& eventually
we'd do this in cases where we used external adaptation to rangify a
non-range type (though that'll be rare))

> Pros:
> - Enables small aesthetic improvements.
> - Would make iterator_range look slightly more "container-like", so it could
> substitute into more template code, though I'd expect templates that take
> read-only containers rather than iterators to be very rare in C++,

This is, hopefully, going to become exceedingly common, actually -
working with ranges is much more convenient than always passing
begin/end (as you've seen with empty) and in the end we hope to have a
lot of range-based algorithms and more range-based adapters.

> and
> templates that take collections and use only begin, end and empty to be
> rarer still.

This would be true, though - currently the range concept is just a
thing that you can call begin(r) and end(r) on, it's unlikely to be
broadened (which is why range-based templates would be more likely to
use something like is_empty as shown above).

> Cons: ?

I haven't gone through all the linked threads just yet (some other
replies pointed out a few prior threads that touched on range
algorithms and empty specifically) but I recall Chandler having some
objections to diving into this sort of thing too quickly as there's
some standardization efforts that he would like to consider before
heading down this path. I'm not personally too fussed about that, but
figured I'd mention it.

- David



More information about the llvm-dev mailing list