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

前端 未结 7 1590
盖世英雄少女心
盖世英雄少女心 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:19

    It really depends on the Container, because the return values of c.Begin() and c.End() are implementation-defined.

    If a list of possible Containers is known to MagicIterator, a wrapper class could be used.

    template
    class MagicIterator
    {
        public:
            MagicIterator(std::vector::const_iterator i)
            {
                vector_const_iterator = i;
            }
    
            // Reimplement similarly for more types.
            MagicIterator(std::vector::iterator i);
            MagicIterator(std::list::const_iterator i);
            MagicIterator(std::list::iterator i);
    
            // Reimplement operators here...
    
        private:
            std::vector::const_iterator vector_const_iterator;
            std::vector::iterator       vector_iterator;
            std::list::const_iterator   list_const_iterator;
            std::list::iterator         list_iterator;
    };
    

    The easy way would be to use a template which accepts Container's type:

    // C++0x
    template
    class Iterator :
        public T::iterator
    {
        using T::iterator::iterator;
    };
    
    for(Iterator i = c.begin(); i != c.end(); ++i)
    {
        // ...
    }
    

    More information here.

提交回复
热议问题