【发布时间】:2020-03-06 15:48:10
【问题描述】:
在C++ template copy constructor on template class,我发现模板复制构造函数不能做。我尝试做到这一点并设法成功。我认为这是因为类中包含移动构造函数。当我评论移动构造函数时,它不会编译: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
问题是:
- 为什么移动构造函数使模板复制构造函数可行?
- 这样做有什么后果吗?这样做安全吗?
- 有没有其他写模板拷贝构造函数的方法?
【问题讨论】:
-
我们可以得到minimal reproducible example 吗?您的代码的修改版本适用于复制出的移动构造函数:coliru.stacked-crooked.com/a/6dbc7966fd21627f
-
如果您希望您的代码与 C++14(由 gcc6.3 使用)一起使用,请制作
matrix::Matrix<double> m1 {m2};。 -
类
T的复制构造函数是一个非模板,它采用T&或const T&类型的参数。任何其他构造函数都不是复制构造函数。 -
@NathanOliver 我在我的电脑上复制了你的代码,它给出了同样的错误。也许是因为编译器。
-
@rafix07 那工作。我尝试使用
matrix::Matrix<double> m1 (m2),这也可以。好像matrix::Matrix<double> m1 = m2被区别对待了,你知道为什么吗?
标签: c++ templates copy-constructor move-constructor