【发布时间】:2009-08-08 20:29:11
【问题描述】:
由于我的一些代码需要在不同类型的矩阵之间进行隐式转换(例如 Matrix<int> 到 Matrix<double>),我定义了一个模板化的复制构造函数 Matrix<T>::Matrix(Matrix<U> const&) 而不是标准的 Matrix<T>::Matrix(Matrix<T> const&):
template <typename T> class Matrix {
public:
// ...
template <typename U> Matrix(Matrix<U> const&);
// ...
private
unsigned int m_rows, m_cols;
T *m_data;
// ...
};
在复制构造函数中添加适当的类型转换后,此方法可以在不同类型的矩阵之间完美转换。令人惊讶的是,在简单的复制构造函数可以运行的情况下,它会因 malloc 错误而失败:U == T。果然,用默认的Matrix<T>::Matrix(Matrix<T> const&)签名重载copy-constructor解决了这个问题。
这是一个糟糕的解决方案,因为它会导致大量复制构造函数代码(字面意思是未更改的复制和粘贴)。更重要的是,我不明白为什么在没有重复代码的情况下会出现 double-free malloc 错误。此外,为什么这里需要极其冗长的 template <typename T> template <typename U> 语法,而不是标准的,更简洁的 template <typename T, typename U>?
模板化方法的完整源代码,在 Mac OS 10.5 上使用 G++ v4.0.1 编译。
template <typename T> template <typename U> Matrix<T>::Matrix(Matrix<U> const& obj) {
m_rows = obj.GetNumRows();
m_cols = obj.GetNumCols();
m_data = new T[m_rows * m_cols];
for (unsigned int r = 0; r < m_rows; ++r) {
for (unsigned int c = 0; c < m_cols; ++c) {
m_data[m_rows * r + c] = static_cast<T>(obj(r, c));
}
}
}
【问题讨论】:
标签: c++ constructor type-conversion copy-constructor