【发布时间】:2016-10-10 11:33:08
【问题描述】:
我有一个矩阵类,我想针对不同的矩阵类型(int、float、double)以不同的方式将矩阵打印到终端。我想实现这个:
- 如果矩阵类型为
int,则使用printf("%d ",matrix[i][j])打印矩阵 - 如果矩阵类型为
float或double,则使用printf("%.3f ",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() 函数(不想复制相同的东西两次)。实现这一目标的最简单方法是什么?谢谢!
【问题讨论】:
标签: c++ class templates object matrix