Simple Matrix Example Using C ++ Template Class
I'm trying to write a trivial Matrix class using C ++ templates, trying to clean up my C ++ and also explaining something to another coder.
This is what I have so far:
template class<T>
class Matrix
{
public:
Matrix(const unsigned int rows, const unsigned int cols);
Matrix(const Matrix& m);
Matrix& operator=(const Matrix& m);
~Matrix();
unsigned int getNumRows() const;
unsigned int getNumCols() const;
template <class T> T getCellValue(unsigned int row, unsigned col) const;
template <class T> void setCellValue(unsigned int row, unsigned col, T value) const;
private:
// Note: intentionally NOT using smart pointers here ...
T * m_values;
};
template<class T> inline T Matrix::getCellValue(unsigned int row, unsigned col) const
{
}
template<class T> inline void Matrix::setCellValue(unsigned int row, unsigned col, T value)
{
}
I'm stuck on ctor as I need to allocate a new [] T, it looks like it should be a templated method. However, I'm not sure if I went through a templated ctor before.
How can I implement ctor?
a source to share
You can access T
in the constructor, so the constructor itself doesn't have to be a template. For instance:
Matrix::Matrix(const unsigned int rows, const unsigned int cols)
{
m_values = new T[rows * columns];
}
Consider using a smart pointer such as boost::scoped_array
or std::vector
to make this array easier to manage resources.
If your matrix is โโof a fixed size, another option is to take rows and columns as template parameters along with T:
template <class T, unsigned Rows, unsigned Columns>
class Matrix
{
T m_values[Rows * Columns];
};
The biggest advantage is that the size is part of the type of the matrix, which can be useful for enforcing rules at compile time, for example, assuming that in matrix multiplication, the two matrices have compatible sizes. It also doesn't require the array to be dynamically allocated, making resource management easier.
The biggest drawback is that you cannot resize the matrix, so it may not work for what you need.
a source to share