
This was inspired by conversations with Greg Law in the lead up to the 2013 ACCU conference.
for (const auto &i : backwards(collection))The simplest implementation of this is shown below:
{
// ... use i ...
}
template <typename T>Of course, this is simplistic. It can be enhanced by making the class support C++11's move semantics, and allowing the wrapper function to return forwarded iterate_backwards. However, this wonderful new C++11 machinery serves to hide the simple intent somewhat, and doesn't win us much since this code optimises away neatly.iterate_backwards
class iterate_backwards
{
public:
explicit(const T &t) : t(t) {} <typename T>
typename T::const_reverse_iterator begin() const { return t.rbegin(); }
typename T::const_reverse_iterator end() const { return t.rend(); }
private:
const T &t;
};
templateiterate_backwards iterate_backwards backwards(const T &t)
{
return(t);
}