A C++ iterator adapter which wraps and hides an inner iterator and converts the iterated type

前端 未结 7 1571
盖世英雄少女心
盖世英雄少女心 2020-12-09 04:25

Having toyed with this I suspect it isn\'t remotely possible, but I thought I\'d ask the experts. I have the following C++ code:

class IInterface
{
    virtual vo         


        
7条回答
  •  粉色の甜心
    2020-12-09 05:11

    Create an abstract IteratorImplementation class:

    template
    class IteratorImplementation
    {
        public:
            virtual ~IteratorImplementation() = 0;
    
            virtual T &operator*() = 0;
            virtual const T &operator*() const = 0;
    
            virtual Iterator &operator++() = 0;
            virtual Iterator &operator--() = 0;
    };
    

    And an Iterator class to wrap around it:

    template
    class Iterator
    {
        public:
            Iterator(IteratorImplementation * = 0);
            ~Iterator();
    
            T &operator*();
            const T &operator*() const;
    
            Iterator &operator++();
            Iterator &operator--();
    
        private:
            IteratorImplementation *i;
    }
    
    Iterator::Iterator(IteratorImplementation *impl) :
        i(impl)
    {
    }
    
    Iterator::~Iterator()
    {
        delete i;
    }
    
    T &Iterator::operator*()
    {
        if(!impl)
        {
            // Throw exception if you please.
            return;
        }
    
        return (*impl)();
    }
    
    // etc.
    

    (You can make IteratorImplementation a class "inside" of Iterator to keep things tidy.)

    In your Container class, return an instance of Iterator with a custom subclass of IteratorImplementation in the ctor:

    class ObjectContainer
    {
        public:
            void insert(Object *o);
            // ...
    
            Iterator begin();
            Iterator end();
    
        private:
            class CustomIteratorImplementation :
                public IteratorImplementation
            {
                public:
                    // Re-implement stuff here.
            }
    };
    
    Iterator ObjectContainer::begin()
    {
        CustomIteratorImplementation *impl = new CustomIteratorImplementation();  // Wish we had C++0x's "var" here.  ;P
    
        return Iterator(impl);
    }
    
        

    提交回复
    热议问题