使两种相同的模板兼容

Making two types of same template compatible

本文关键字:两种      更新时间:2023-10-16

我不知道如何命名我面临的问题。因此,我有一个用于矩阵的模板类,可以接受不同类型的类型,例如int,双重和其他东西。我的问题是,如果我想从事类的不同实例类型,我将无法编译。这是添加函数的定义,据说应该在当前实例中添加矩阵。

template <class T>
void Matrix<T>::add(const Matrix &m) {
    for (int i = 0; i < this->rows; ++i) {
        for (int j = 0; j < this->cols; ++j) {
            this->mat[i][j] += m.at(i,j);
        }
    }
}

它可以很好地工作,例如如果我将Matrix<double>添加到Matrix<double>实例。

,但我无法使其工作,将Matrix<int>添加到Matrix<double>,例如:

Matrix<double> matA(2,2);
Matrix<int> matB(2,2);
matA.add(matB);

编译器(G 4.8)抱怨:

error: no matching function for call to ‘Matrix<double>::add(Matrix<int>&)

可以解决什么?

在类模板中,模板名称是当前实例化的快捷方式。也就是说,MatrixMatrix<T>相同。因此,通过声明void add(const Matrix& m);,您可以说您可以添加同一类型的另一个矩阵。

如果您希望能够添加任意类型的另一个矩阵,则需要为其引入另一个模板参数。

template <class T>
class Matrix {
    // ...
public:
    template <class U>
    void add(const Matrix<U>& m);
};
template <class T> template <class U>
void Matrix<T>::add(const Matrix<U>& m) {
    // ...
}