I wrote a short utility function an object to “wrap” an iterable container, so that I could walk it backwards using a range based for.
template <typename Iterable>
struct ReverseWrapper {
private:
Iterable& m_iterable;
public:
ReverseWrapper(Iterable& iterable) : m_iterable(iterable) {}
auto begin() const ->decltype(m_iterable.rbegin()) {
return m_iterable.rbegin();
}
auto end() const ->decltype(m_iterable.rend()) {
return m_iterable.rend();
}
};
template <typename Iterable>
ReverseWrapper<Iterable> reverseIterate(Iterable& list) {
return ReverseWrapper<Iterable>(list);
}
This works for C++ iterable objects, but not for static arrays. What is required for an object to support iteration using a range based for? What would be the best way to approach this problem?
The actual rule to choose
beginandendfunctions for iterables is the following: use the classbeginandendfunction if it has some. Use overloads of the global functionsstd::beginandstd::endif some are provided.Static arrays not being class/struct, they don’t/can’t have member functions. The functions called by the foreach loop are the global functions
std::beginandstd::end, taking an array as parameter. Assumingstd::rbeginandstd::rendexisted, you would have to construct your wrapper the following way:Even though
std::rbeginandstd::rendexist in the c++14 standard, they are not available in the c++11 one. So, to get the above code to work with c++11, you would have to implement these functions by hand: