[英]C++ template copy constructor
在模板类上的 C++ 模板复制构造函数中,我发现无法完成模板复制构造函数。 我尝试这样做并设法成功。 我认为这是因为类中包含移动构造函数。 当我评论移动构造函数时,它不会编译: error: use of deleted function 'matrix::Matrix<TYPE>::Matrix(const matrix::Matrix<TYPE>&) [with TYPE = double]
。 我在 Windows 10 上使用 MinGW(GCC 6.3.0)。
标题:
namespace matrix {
enum IDENTITY { BLANK, I_1, I_2, I_3, I_4};
template<class TYPE = double>
class Matrix {
public:
Matrix(const Matrix& m) = delete; //delete normal copy constructor
template <class U> Matrix(const Matrix<U>& m); //template copy constructor
~Matrix();
Matrix(Matrix&& m) noexcept{ //move constructor
std::cout << "Move constructor" << std::endl;
}
.
.//Some other functions declaration
.
private:
unsigned int rows_ = 0;
unsigned int cols_ = 0;
TYPE *data_;
};
.
.//Member functions definition
.
主要的:
int main(){
matrix::Matrix<int> m2(matrix::I_4); //normal constructor, Identity matrix 4x4
matrix::Matrix<double> m1 = m2; //copy constructor, error here if without move constructor
m1(0,1) = 2; //assign m1(0,1) = 2
//show matrix
std::cout << m1;
std::cout << m2;
}
结果:
1 2 0 0
0 1 0 0
0 0 1 0
0 0 0 1
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
Process returned 0 (0x0) execution time : 0.062 s
问题是:
我认为,您定义了一个“构造函数”。 它不是“复制构造函数”。 以下错误是它的结果: - 如果您只声明移动构造函数(没有复制构造函数),则复制构造函数被“删除”。 - 如果您定义了“任何构造函数”,那么编译器会创建默认的复制构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.