我有一个矩阵类,我想针对不同的矩阵类型(int、float、double)以不同的方式将矩阵打印到终端。我想实现这个:
- 如果矩阵类型 if
int
, 使用printf("%d ",matrix[i][j])
打印矩阵 - 如果矩阵类型 if
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)
.但是,我希望有一个共同的 print()
两者的功能 float
和 double
类型矩阵(不想复制相同的东西两次)。实现这一目标的最简单方法是什么?谢谢!
最佳答案
作为提议的模板化解决方案的替代方案,使用旧的好函数重载:
public:
void print() const
{
for (auto const& row : matrix)
for (auto const& v : row)
print(v);
}
private:
static void print(int val)
{
printf("%d ", val);
}
static void print(float val)
{
printf("%.3f", val);
}
关于c++ - 类型组的模板类的成员特化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39957305/