Reputation: 5132
Are there any suggestions on how to use a nested class iterator
in an ABC in C++ ? Note that, I also want to have a virtual function returning an
instance of this class.
More specifically here's my approach:
class ABC {
typedef iterator<forward_iterator_tag, MyType> MyTypeIter;
virtual MyTypeIter *begin() = 0;
};
class Foo : ABC {
MyTypeIter : public ABC::MyTypeIter;
virtual MyTypeIter *begin();
};
ABC::MyTypeIter *Foo::begin()
{
Foo::MyTypeIter *ret;
ret = new Foo::MyTypeIter(...);
return ret;
}
Is there a better approach than this (e.g. one that does not use pointers) ?
Upvotes: 2
Views: 1234
Reputation: 43110
I prefer to keep iterators interal to the class and exposing only an interface for iteration.
For example, you can implement a List<>
with the methods:
void prepare_iteration() // reset the internal iterator
bool step_iteration() // move internal iterator
DATA_TYPE & read() // return the data by using the iterator
write( DATA_TYPE & ) // update the data by using the iterator
In this example the iterator can be a simple node pointer and it's never exposed to the user.
I find this approach much easier and safer than iterator objects.
(well the 'safer' part needs a lot of discussion)
I know that's not the answer that you are looking for but it's just an alternative idea to design your classes.
Upvotes: 0
Reputation: 2381
What is your problem? A nested class behaves the same way as a top-level class, so you may return its objects just as you would have returned any other.
Upvotes: 1
Reputation: 14341
Take a look on how iterators are implemented for std::vector class, for example.
Upvotes: 0