samedi 24 janvier 2015

Issues with constructors for nested class of a template (copy ctor seems to override other ctor)

I have a homework assignment to do a template class of a Matrix, which includes some pretty basic and simple stuff. We also need to create a forward iterator class for it (a nested one) which behaves in a standard way, it should specifically support a copy constructor.


Here is the relevant matrix.h code:



template<class T>
class Matrix
{
public:
//nested iterator class
class iterator
{

public:
typedef iterator self_type;
typedef T value_type;
typedef T& reference;
typedef T* pointer;
typedef std::vector<T>& vector;

iterator(Matrix &other, int index) :
_currIndex(index), _currMatrix(other)
{

}

iterator(iterator& other) :
_currIndex(other._currIndex), _currMatrix(other._currMatrix)
{

}
private:
int _currIndex;
Matrix<T>& _currMatrix;
}

//function that creates an iterator for the current matrix
iterator begin()
{
return iterator(*this, 0);
}

iterator end()
{
return iterator(*this, _data.size());
}

private:
unsigned int _rows;
unsigned int _cols;
vector<T> _data;
}


Matrix has several constructors like copy, empty etc. They initialize the private members and nothing else. The iterator class also overloads the ++ operator


The problem I'm facing is with compiling the following code in Linux using g++:



for(auto it = m.begin(); it != m.end(); it++)
{
cout << *it;
}


On windows, in Visual Studio the code compiles and runs OK with no issues. On linux, when compiling the following error pops up:



debug.cpp: In function ‘int main()’:
debug.cpp:63:24: error: no matching function for call to ‘Matrix<int>::iterator::iterator(Matrix<int>::iterator)’
for (auto it = m.begin(); it != m.end(); it++)
^
debug.cpp:63:24: note: candidates are:
In file included from debug.cpp:11:0:
matrix.h:35:3: note: Matrix<T>::iterator::iterator(Matrix<T>::iterator&) [with T = int]
iterator(iterator& other) :
^
matrix.h:35:3: note: no known conversion for argument 1 from ‘Matrix<int>::iterator’ to ‘Matrix<int>::iterator&’
matrix.h:29:3: note: Matrix<T>::iterator::iterator(Matrix<T>, int) [with T = int]
iterator(Matrix other, int index) :
^
matrix.h:29:3: note: candidate expects 2 arguments, 1 provided


If I comment out the copy constructor for the iterator class, then the code compiles fine on Linux (and windows). If I keep both constructors, then g++ throws the error. Its as if the copy constructor is overriding the previous constructor and I have no idea why.


Can anyone share some insight as to why this is happening? maybe how I can fix it?


Aucun commentaire:

Enregistrer un commentaire