Iterator for a custom container with derived classes

I have a custom container that is implemented in two different ways, but with one interface. something like that.

    class Vector 
    {
       virtual Iterator begin() = 0;
       virtual Iterator end () = 0 ;

    ... // some more functions.
    } ;

    class VectorImplA : public Vector
    {
       Iterator begin() { return m_data.begin() ; }
       Iterator end () { return m_data.end() ; }
    private:
       SomeFloatContainer m_data ;
    } ;

    class VectorImplB : public Vector
    {
       Iterator begin() { return m_data.end() ; }
       Iterator end() ; { return m_data.end() ; }


    private:
        std::vector <float> m_data ;

    } ;

I need a unified interface for Iterator, so that I can use it in the base class. Any ideas?

+4
source share
3 answers

I faced exactly this problem before. Although there are ways to solve your problem, you should probably give up the idea of ​​a vector base class. Instead, you should probably imitate the way you create the c ++ STL container.

STL , . std::vector Container, Container. - , . . , , Container.

Container, , , typedef value_type, typedef iterator const_iterator. , begin() end(), , ..

, Vector, , , . , . , STL, . , STL, , , STL (, std::sort) .

:

class VectorImplA
{
public:
    typedef VectorImplAIterator iterator;

    iterator begin();
    iterator end();
};

class VectorImplB
{
public:
    typedef VectorImplBIterator iterator;

    iterator begin();
    iterator end();
};

template <typename VectorConcept>
void doSomeOperations(VectorConcept &container)
{
    VectorConcept::iterator it;
    it = container.begin();
}

int main()
{
    VectorImplA vecA;
    VectorImplB vecB;
    doSomeOperations(vecA); // Compiles!
    doSomeOperations(vecB); // Compiles as well!
}

, , ( !):

struct IteratorBase
{
    virtual void next() = 0;
};

struct IteratorA : IteratorBase
{
    void next() {};
};

struct IteratorB : IteratorBase
{
    void next() {};
};

class Iterator
{
    IteratorBase *d_base;
public:
    void next() { d_base->next(); }
};
+8

. , , .
, "" , .

0

I had the same problem before. I used solution # 2 with a slight modification in the definition of the Iterator class

class Iterator :public boost::iterator_facade<Iterator,element_type, forward_traversal_tag>
{
  ...
}

Thus, I was able to use STL algorithms with my containers.

0
source

Source: https://habr.com/ru/post/1731183/


All Articles