2

I'm trying to write class similar to std::vector, which would contain an Iterator as inner class. For some member functions of Iterator I would like to access variables from my Vector class. For example when overloading operator++ I would like to check if index of Iterator doesn't exceed size of Vector (and if so throw std::out_of_range()). I've implemented this access to outer class variable based on this topic. But for some reason compiler throws following error at me:

error C2440: '': cannot convert from 'initializer list' to 'Vector::Iterator'

Here is minimal version of my code replicating the issue:

template <typename Type>
class Vector
{
public:
    class Iterator;
    Vector() : size(0), capacity(0), data(nullptr) {}
    Iterator begin()
    {
        return Iterator(this, 0);
    }
private:
    size_t size, capacity;
    Type* data;
};

template <typename Type>
class Vector<Type>::Iterator
{
public:
    Iterator(Vector& vectorRef, size_t index) : vectorRef(vectorRef), index(index) {}
private:
    size_t index;
    Vector& vectorRef;
};

int main()
{
    Vector<int> vec;
    vec.begin();
    return 0;
}

What would be the cause of this? And does it make sense to pass reference to Vector class like that? Or is there a better way?

Stormwaker
  • 381
  • 2
  • 12

1 Answers1

1

That's because this has type Vector* or const Vector* but your constructor is accepting a Vector& so no matching constructor is found.

Try with Vector(*this, 0).

Jack
  • 131,802
  • 30
  • 241
  • 343
  • Thank you. I'm still mixing up uses of pointers and reference sometimes. Dereferencing "this" didn't fix the issue, but I changed type of vectorRef to Vector* and at least it's compiling. Going to test it now. – Stormwaker Dec 09 '18 at 12:23
  • Ok. Tested it again and it works with dereferencing "this" like you suggested as well. Thank you again. – Stormwaker Dec 09 '18 at 12:42