Search code examples
c++templatesvectoriteratortemplate-classes

C++ Can you make an iterator of a template class?


I'm working on a class project and for it for it we have to make a template class that is derived from vector and then be able to add and remove elements from it.

I thought I would make and iterator of the class since it is a vector I thought I should just be able to use "this" and create the iterator but "this" is a pointer so that didn't work.

If I try this:vector<T>::iterator p; I get plenty of errors so can I even do this or do I just need to find a different solution?


Solution

  • First of all, you should not inherit from std::vector as it does not have a virtual destructor. For more info see Thou shalt not inherit from std::vector.

    If you want to use the iterator from std::vector you have to import it into your class' scope with the using directive.

    #include <vector>
    
    template < typename T >
    class MyVector : std::vector<T>
    {
    public:
      using typename std::vector<T>::iterator;
    };
    
    int main()
    {
      MyVector<double>::iterator p;
    }