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

Duncan P. N. Exon Smith dexonsmith at apple.com
Wed Mar 19 11:57:26 PDT 2014


On Mar 19, 2014, at 11:32 AM, Aaron Ballman <aaron at aaronballman.com> wrote:

> 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: ?

I’m in favour.

> 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.

There are a couple of proposals [1][2] that I can find.  It sounds like the
exact set of methods to provide is somewhat contentious [3].  empty() seems
pretty innocuous though.  Note that the standard proposals use std::range
instead of std::iterator_range.

In my opinion, other methods (e.g., front(), back(), and (for random access
iterators) operator[]) would also be useful.

[1]: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1871.html
[2]: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3350.html
[3]: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3513.html#range-arg



More information about the llvm-dev mailing list