使用C++模板类的简单矩阵示例

问题描述:

我正在尝试编写一个普通的Matrix类,使用C++模板尝试刷新我的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) 
{ 
} 

我卡上的构造函数,因为我需要分配一个新的[] T,它看起来像它需要一个模板方法 - 然而, ,我不确定我以前是否已经过模板化的ctor。

我该如何实现ctor?

+1

使用复选标记不要忘记接受以前问题的答案。请参阅*上的常见问题解答*“如何在此提问?”*了解更多详情。 – 2010-04-20 23:20:11

+0

你对'getCellValue'和'setCellValue'的声明不正确 - 你不需要(也不能)在它们前面有模板。 另外,当你想在类外定义它们时,它需要读取'template inline T Matrix :: getCellValue(unsigned int row,unsigned col)const' – rlbond 2010-04-20 23:34:13

+0

@rlbond:谢谢你指出。我想我的C++比我想象的更生锈...... – skyeagle 2010-04-21 00:14:16

您可以在构造函数访问T,所以构造函数本身不需要是一个模板。例如:

Matrix::Matrix(const unsigned int rows, const unsigned int cols) 
{ 
    m_values = new T[rows * columns]; 
} 

考虑使用智能指针,像boost::scoped_arraystd::vector为阵,使资源管理更容易一点。

如果你的矩阵具有固定的大小,另一种选择是采取的行和列作为模板参数和T一起:

template <class T, unsigned Rows, unsigned Columns> 
class Matrix 
{ 
    T m_values[Rows * Columns]; 
}; 

的最大优点是尺寸那么一个类型的一部分矩阵,它可以用于在编译时执行规则,例如,在进行矩阵乘法时确保两个矩阵的大小兼容。它也不需要动态分配数组,这使得资源管理更容易一些。

最大的缺点是你不能改变矩阵的大小,所以它可能无法满足你的需求。

+0

@james:感谢您的快速响应。我更喜欢第一种方法(尽管我可以看到另一种方法的吸引力)。最后一个问题(采用第一种方法) - 你确定ctor可以访问T(我以前从未见过)。此外,它是否是一个模板函数(签名暗示它不是)。所以(假设它不是一个方法模板,我可以在我的源文件(而不是头部)中实现它吗? – skyeagle 2010-04-20 23:12:05

+0

@skyeagle:你可以在类模板定义中的任何地方使用'T'。构造函数不是模板,但因为它是类模板的成员函数,所以它必须在头文件中实现。MSDN有一个相当不错的类模板成员函数示例:http://msdn.microsoft.com/en-us/library/80dx1bas (VS.100).aspx – 2010-04-20 23:16:18

+0

非常重要 - 如果你使用'new []',你需要使用'scoped_array'。 另外,我推荐使用'vector'而不是数组。 – rlbond 2010-04-20 23:33:01