[英]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.