tags:

views:

186

answers:

2

I have code that looks like this:

template<class T>
class list
{
public:
    class iterator;
};

template<class T>
class list::iterator
{
public:
    iterator();
protected:
    list* lstptr;
};

list<T>::iterator::iterator()
{
    //???
}

I want to make the constructor of list::iterator to make iterator::lstptr point to the list it's called from. I.e.:

list xlst;
xlst::iterator xitr;
//xitr.lstptr = xlst

How would I do that?

And also, am I referencing my iterator-constructor right, or should I do something like this:

template<class T>
class list<T>::iterator
{
public:
    list<T>::iterator();
protected:
    list* lstptr;
};
+3  A: 

You can pass the list to the constructor of iterator:

list xlst;
list::iterator xitr(xlst);

Or, you could make an iterator factory function:

list xlst;
list::iterator xitr = xlst.create_iter();

In the factory function case, the create_iter() function can use this to refer to the enclosing list.

Greg Hewgill
Yeah, I was about to do that, until I relized I should be able to make the iterator equal to it's calling class.Then I reade your answer and relized that I would call iterator with "list::iterator" and not "xlst::iterator". My goal was to recreate some aspects of "vector".
Keand64
A: 

Since you don't need to change (reseat) the pointer and there's no need for the NULL value, I would instead use a reference. Also you can use an initializer list when assigning the member variable (and have to if you're using a reference).

template<class T>
class list::iterator
{
public:
    iterator( list& parent ) : lstptr( parent ){}

protected:
    list& lstptr;
};

And as mentioned before: use a factory method inside the list class to construct objects of type list::iterator.

ziggystar