On 2015-02-20 14:42, Thiago Macieira wrote: > On Friday 20 February 2015 12:53:24 Matthew Woehlke wrote: >> for (auto const i : qtEnumerate(map)) >> >> Maybe it would be nice for Qt to provide one or both of these? > > Sounds easy enough. Want to give it a try?
I'm happy to give you my headers; not sure when/if I'd have time to clean them up as actual patches against Qt, however. For enumerate, though, I technically need the customer's permission to share it. > Note that this should also work for foreach: > > foreach (const auto i, qtEnumerate(map)) > > Something like: > > template <typename Map> > struct QEnumerateMap : private Map > { > struct const_iterator { > typename Map::iterator i; > iterator(typename Map::iterator i) : i(i) {} > > // need to return by value > std::pair<typename Map::key_type, typename Map::value_type> > value() const > { return std::make_pair(i.key(), i.value()); } > }; > > const_iterator begin() const > { return iterator(Map::begin()); } > const_iterator end() const > { return iterator(Map::end()); } > }; No, that doesn't seem right at all (unless you were going for a non-broken cref?). The way I did it is I construct a minimal class that has a reference to the map (though, as discussed, this might need to be a copy), containing a private iterator type, and begin()/end() methods. The private iterator type is constructed from the container iterator, and needs to implement its own operator++, operator== and operator*. The last one is key; it returns the underlying iterator, rather than value() of the same. Index range works on basically the same idea, only the 'underlying iterator' is a number, you construct it from a number, and begin() returns an iterator(0) while end returns an iterator(m_end). The iterator needs the same operators, with the obvious implementations. This all works with range-based for. Not sure about foreach... One thing I notice you *did* get right is separating the utility class from the function to create it; you do need to do this for template deduction. -- Matthew _______________________________________________ Development mailing list Development@qt-project.org http://lists.qt-project.org/mailman/listinfo/development