使两种相同的模板兼容
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>&)
可以解决什么?
在类模板中,模板名称是当前实例化的快捷方式。也就是说,Matrix
与Matrix<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) {
// ...
}
相关文章:
- 在C++中将函数压缩为两种方式
- 如何使映射键具有两种不同的数据类型?
- 两种访问I2C总线的方法有什么区别?
- 两种模板示例有什么区别?
- 如何构造可以调用和返回两种不同类型的模板
- 这两种C++语法之间有什么区别?
- 为什么两种不同的对象初始化方式给出不同的输出
- std::cin 从控制台获取两种不同的变量类型,'storing'以后使用第二种类型?
- 定义类模板构造函数的两种方法之间的区别
- 初始化类的两种方法?
- C++ 一个函数,可以根据接受的值返回两种类型之一
- 如何检查程序员在C++中提供的两种不同格式的输入
- C++指针中的这两种类型的值分配有什么区别?
- 如何在c ++中以一行(水平)打印两个文件的数据?如给定的.这两种形式来自两个不同的文本文件
- 有没有办法让C++函数采用具有相同成员的两种不同类型?
- C++两种类型相互依赖
- 两种情况下的输出不应该相同吗?
- C++:这两种将数字写入矩阵的方式之间是否存在显着的速度差异?
- 在没有堆的情况下用两种方法构造对象
- 如何调试两种语言的程序