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

Aaron Ballman aaron at aaronballman.com
Wed Mar 19 11:32:14 PDT 2014


On Wed, Mar 19, 2014 at 2:13 PM, 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.
>
> 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++, and
> templates that take collections and use only begin, end and empty to be
> rarer still.
>
> Cons: ?

This is a pattern I ran into a handful of times when range-ifying
parts of clang (but not so frequently that I felt it was a major win),
so I'm roughly in favor of the API. However, if there's been
standardization efforts for range, we should be sure that we're doing
something compatible there.

~Aaron



More information about the llvm-dev mailing list