Search code examples
c++iteratorstdlist

How can I support Range-based for Statement for an internal list? ( c++ )


We have some widely used classes that wrap an internal std::list

template <class COLL_TYPE>
class OurColl
{
...
    private:
    std::list<COLL_TYPE> *m_pList;

I'd like to be able to use the range based for loops:

OurColl<int> listInts;
for ( int x : listInts )
{

}

This would have to iterate over the underlying m_pList.

I feel this question is different enough since it is closest to the answer provided by Chris Redford at the bottom of the question marked as duplicate.

Also, there is a bit of a twist since I am in a class with a template wrapping an internal list.


Solution

  • This seems to work:

      typename std::list<COLL_TYPE>::iterator begin()
       {
          return m_pList->begin();
       }
       typename std::list<COLL_TYPE>::iterator end()
       {
          return m_pList->end();
       }
       typename std::list<COLL_TYPE>::const_iterator begin() const
       {
          return m_pList->begin();
       }
       typename std::list<COLL_TYPE>::const_iterator end() const
       {
          return m_pList->end();
       }