Suppose I have a class of complex numbers called Complex
and I wish to implement a class of generic matrices with transpose operation.
double
s and int
s don't require special care, but you have to calculate the conjugate of complex numbers to transpose. Therefore, I implemented a "specialized transpose()
".
template <class T>
Matrix<T> Matrix<T>::transpose() const
{
Matrix<T> matrix(_cols, _rows);
unsigned int i, j;
for (i = 0; i < _rows ; ++i)
{
for (j = 0; j < _cols; ++j)
{
matrix(j, i) = (*this)(i, j);
}
}
return matrix;
}
template <>
Matrix<Complex> Matrix<Complex>::transpose() const
{
Matrix<Complex> matrix(_cols, _rows);
unsigned int i, j;
for (i = 0; i < _rows ; ++i)
{
for (j = 0; j < _cols; ++j)
{
matrix(j, i) = (*this)(i, j).conj();
}
}
return matrix;
}
As you can see, there's a severe code repetition. Is there any way I can deal with it (like using helper methods)?
References from Wikipedia: