我有一個矩陣類,我想打印到不同的矩陣類型(int,float,double)不同的矩陣到終端。我想實現這一點:如果矩陣類型,如果float
或double
,打印矩陣使用printf("%.3f ",matrix[i][j])
成員專業化的模板類爲組類?
int
,打印矩陣使用printf("%d ",matrix[i][j])
- ,拋出一個錯誤
以下是我所擁有的相關部分:
...
template <class T>
class Matrix2D {
private:
std::vector< std::vector<T> > matrix;
public:
...
void print() const; // print the whole matrix
}
...
template <class T>
void Matrix2D<T>::print() const {
// throw an error
}
template <>
void Matrix2D<int>::print() const {
// print matrix using printf("%d ",matrix[i][j])
}
template <>
void Matrix2D<float,double>::print() const {
// print matrix using printf("%.3f ",matrix[i][j])
}
但使用Matrix2D<float,double>
給我錯誤信息error: wrong number of template arguments (2, should be 1)
。但是,我希望float
和double
型矩陣具有共同的print()
函數(不希望兩次複製相同的東西)。達到此目的最簡單的方法是什麼?謝謝!
這是我落得這樣做吧。這是一個輕量級解決方案,避免了額外的庫。我可以將大部分的顯示功能寫入一塊,並調用此重載打印功能,從而最大限度地減少額外的代碼寫入。 –