c++ - 类型组的模板类的成员特化?

标签 c++ class templates object matrix

我有一个矩阵类,我想针对不同的矩阵类型(int、float、double)以不同的方式将矩阵打印到终端。我想实现这个:

  • 如果矩阵类型 if int , 使用 printf("%d ",matrix[i][j]) 打印矩阵
  • 如果矩阵类型 if floatdouble , 使用 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()两者的功能 floatdouble类型矩阵(不想复制相同的东西两次)。实现这一目标的最简单方法是什么?谢谢!

最佳答案

作为提议的模板化解决方案的替代方案,使用旧的好函数重载:

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/

相关文章:

templates - 可扩展的临时多态性? (C++11)

python - Django 中的模板不存在

c++ - 调用和重载模板函数

c++ - 像 Photoshop 质量一样将 PDF 转换为 JPG - 商业 C++/Delphi 库

C++ 编译器错误消息

c++ - G726 ADPCM缓冲怎么玩?

javascript - CoffeeScript 有类析构函数吗?

java - 无法运行我的类(class)

c++ - CPLEX C++ 接口(interface) : How to get the index of a violated constraint?

Python;类实例