2

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.

Derek
  • 7,615
  • 5
  • 33
  • 58
  • Please excuse my curiosity, but why do you have a *pointer* to a list? If you don't have a pointer, you could live by [the rule of zero](http://en.cppreference.com/w/cpp/language/rule_of_three#Rule_of_zero) which will make your life (and the class) simpler. – Some programmer dude Nov 30 '16 at 12:01
  • The important parts is that you need a `begin` and `end` functions that returns an object that is forward iterable. This is what the answers in the duplicate states (in a perhaps long-winded way). The simplest way to do it in this case is to use the wrapped lists iterators. – Some programmer dude Nov 30 '16 at 12:21
  • Does my example code look right? This is very old code that is widely used in our projects, I'm hoping to make it a bit easier to use. – Derek Nov 30 '16 at 12:28

1 Answers1

0

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();
   }
Derek
  • 7,615
  • 5
  • 33
  • 58