Trying to write a std::iterator : Compilation error

Posted by Naveen on Stack Overflow See other posts from Stack Overflow or by Naveen
Published on 2010-03-31T09:14:53Z Indexed on 2010/03/31 9:23 UTC
Read the original article Hit count: 327

Filed under:
|
|

I am trying to write an std::iterator for the CArray<Type,ArgType> MFC class. This is what I have done till now:

template <class Type, class ArgType>
class CArrayIterator : public std::iterator<std::random_access_iterator_tag, ArgType>
{
public:
    CArrayIterator(CArray<Type,ArgType>& array_in, int index_in = 0)
        : m_pArray(&array_in), m_index(index_in)
    {
    }

    void operator++() { ++m_index; }
    void operator++(int) { ++m_index; }
    void operator--() { --m_index; }
    void operator--(int) { --m_index; }
    void operator+=(int n) { m_index += n; }
    void operator-=(int n) { m_index -= n; }
    typename ArgType operator*() const{ return m_pArray->GetAt(m_index); }
    typename ArgType operator->() const { return m_pArray->GetAt(m_index); }
    bool operator==(const CArrayIterator& other) const
    {
        return m_pArray == other.m_pArray && m_index == other.m_index;
    }
    bool operator!=(const CArrayIterator& other) const
    {
        return ! (operator==(other));
    }

private:
    CArray<Type,ArgType>* m_pArray;
    int m_index;
};

I also provided two helper functions to create the iterators like this:

template<class Type, class ArgType>
CArrayIterator<Type,ArgType> make_begin(CArray<Type,ArgType>& array_in)
{
    return CArrayIterator<Type,ArgType>(array_in, 0);
}

template<class Type, class ArgType>
CArrayIterator<Type,ArgType> make_end(CArray<Type,ArgType>& array_in)
{
    return CArrayIterator<Type,ArgType>(array_in, array_in.GetSize());
}

To test the code, I wrote a simple class A and tried to use it like this:

class A
{
public:
    A(int n): m_i(n)
    {
    }

    int get() const
    {
        return m_i;
    }

private:
    int m_i;
};
struct Test
{
    void operator()(A* p)
    {
        std::cout<<p->get()<<"\n";
    }
};

int main(int argc, char **argv) 
{
    CArray<A*, A*> b;

    b.Add(new A(10));
    b.Add(new A(20));

    std::for_each(make_begin(b), make_end(b), Test());
        return 0;
}

But when I compile this code, I get the following error:

Error 4 error C2784: 'bool std::operator <(const std::_Tree<_Traits> &,const std::_Tree<_Traits> &)' : could not deduce template argument for 'const std::_Tree<_Traits> &' from 'CArrayIterator' C:\Program Files\Microsoft Visual Studio 9.0\VC\include\xutility 1564 Vs8Console

Can anybody throw some light on what I am doing wrong and how it can be corrected? I am using VC9 compiler if it matters.

© Stack Overflow or respective owner

Related posts about c++

Related posts about stl