simonstuck
simonstuck

Reputation: 58

Custom Iterator for Template

I am currently trying to build an iterator for a custom class and it's not going particularly well: The problem I'm having is that I my custom class uses a template and looks something like this:

template<class T>
class MyClass {
private:
    T memberVar;
};

Now, MyClass is basically a wrapper for memberVar which at the moment is a map or a map of maps. Now, I would like to create an iterator in another class and do useful things with it, i.e. access elements in my map or map of maps.

I have tried forwarding my iterator from my map, which doesn't give me an error in MyClass when I do something like typedef T::iterator iterator;, but it obviously doesn't want to be nice to me when I want to call myIterator->first, because now it doesn't believe me anymore that this will work. To be honest, I was surprised to see that my typedef actually works.

Now my question: Is there a nice way to do what I would like to do? Or have I manoeuvred myself into a corner here? Thanks very much in advance!

Simon

Some more information:

In a ClassA I instantiate a ClassB which then inherits MyClass with the right type T. Then, in ClassA I also instantiate a ClassC which I give a reference to ClassB. Now, the error occurs, when I try to create myIterator in ClassC and try to do myIterator->first.

Upvotes: 0

Views: 191

Answers (1)

James Kanze
James Kanze

Reputation: 153899

For starters, if your class template is always going to be a wrapper for some instantiation of map, I'd repeat all of the typedefs in std::map in your class, each time with:

typedef typename T::value_type;
// ...

(The typename is necessary, at least according to the standard, but version of g++, and compile all of your code with it, even if you use a different compiler for the final builds.)

With regards to the myIterator->first not working, you'll have to tell me where this line occured. There should be no problem if it is in a function in your class template, because the function shouldn't be instantiated until it is used (and by that type, the type of T is known). If it is outside of the class template, it should still work, provided you've declared the variable correctly, something like:

MyClass<std::map<T1, T2> >::iterator myIterator;

(Within the class template, just using iterator as the typename should suffice, since the typedef is in scope.)

Upvotes: 1

Related Questions