2010-04-20 102 views
2

我正在嘗試編寫一個普通的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

回答

5

您可以在構造函數訪問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