template <class T>
template <class U> Matrix<T>& Matrix<T>::operator = (const Matrix<U>& mat) {
if (sizeof(T) != sizeof(U)) {
size_t i,j;
// Free memory
free(matrix);
// Set new rows and columns
m = mat.row();
n = mat.col();
// Allocate memory for matrix
matrix = (T*)malloc(m*n*sizeof(T));
for (i=0;i<m;i++) {
for (j=0;j<n;j++) {
*(matrix+n*i+j) = *(mat.data()+n*i+j);
}
}
}
else {
if (this != &mat) {
// Free memory
free(matrix);
// Set new rows and columns
m = mat.row();
n = mat.col();
// Set matrix to copy of mat
memcpy(matrix, mat.data(), m*n*sizeof(T));
}
}
return *this;
}
In file included from Matrix.h:118:0,
from Main.cpp:4:
Matrix.cpp: In instantiation of ‘Matrix<T>& Matrix<T>::operator=(const Matrix<U>&) [with U = int; T = double]’:
Main.cpp:15:8: required from here
Matrix.cpp:533:5: error: passing ‘const Matrix<int>’ as ‘this’ argument of ‘size_t Matrix<T>::row() [with T = int; size_t = long unsigned int]’ discards qualifiers [-fpermissive]
m = mat.row();
^
Matrix.cpp:534:5: error: passing ‘const Matrix<int>’ as ‘this’ argument of ‘size_t Matrix<T>::col() [with T = int; size_t = long unsigned int]’ discards qualifiers [-fpermissive]
n = mat.col();
^
Matrix.cpp:546:12: error: comparison between distinct pointer types ‘Matrix<double>*’ and ‘const Matrix<int>*’ lacks a cast
if (this != &mat) {
^
Matrix.cpp:551:6: error: passing ‘const Matrix<int>’ as ‘this’ argument of ‘size_t Matrix<T>::row() [with T = int; size_t = long unsigned int]’ discards qualifiers [-fpermissive]
m = mat.row();
^
Matrix.cpp:552:6: error: passing ‘const Matrix<int>’ as ‘this’ argument of ‘size_t Matrix<T>::col() [with T = int; size_t = long unsigned int]’ discards qualifiers [-fpermissive]
n = mat.col();
^
You need to check methods row() and col(), they ought to be const members, but they aren't.
You can only compare mat and *this if they're the same type. I think this is the problem you can see. You can work around it by reinterpreting those addresses as some suitably large integral type, but you have a real problem, that memcpy only works if T and U are the same type and a POD type. You should try to support user-defined types with template classes/functions.
They weren't const. That was a major error. And now the only thing is it says I can't compare pointers of different types but that check only happens if T == U which means they will be of the same type. But I know the compiler can't tell that. Maybe I could rearrange my logic and do a cast of the pointer.
EDIT: if (this != reinterpret_cast<Matrix<T>*>(const_cast<Matrix<U>*>(&mat)))
That's what I have but I just feel like its bad programming practice.