我正在尝试编写一个简单的Matrix类,使用C++模板试图刷新我的C++,并向同伴编写解释.
这就是我所看到的:
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)
{
}
Run Code Online (Sandbox Code Playgroud)
我被困在ctor上,因为我需要分配一个新的[] T,看起来它需要一个模板方法 - 但是,我不确定我是否曾经遇到过一个模板化的ctor.
我怎样才能实现ctor?
您可以T在构造函数中访问,因此构造函数本身不需要是模板.例如:
Matrix::Matrix(const unsigned int rows, const unsigned int cols)
{
m_values = new T[rows * columns];
}
Run Code Online (Sandbox Code Playgroud)
考虑使用智能指针,boost::scoped_array或者像std::vector数组一样,使资源管理更容易一些.
如果您的矩阵具有固定大小,则另一个选项是将行和列作为模板参数与T一起使用:
template <class T, unsigned Rows, unsigned Columns>
class Matrix
{
T m_values[Rows * Columns];
};
Run Code Online (Sandbox Code Playgroud)
最大的优点是大小是矩阵类型的一部分,这对于在编译时强制执行规则很有用,例如,确保两个矩阵在进行矩阵乘法时具有兼容的大小.它也不需要动态分配数组,这使资源管理更容易一些.
最大的缺点是您无法更改矩阵的大小,因此可能无法满足您的需求.