3つの行列を足し算する版できた.
元ネタ
http://itee.uq.edu.au/~conrad/misc/sanderson_templates_lecture_uqcomp7305.pdf
#include<iostream>
template < typename T1, typename T2 >
class Glue;
class Matrix {
public:
int rows;
int cols;
double *data;
Matrix(){}
Matrix( int in_row, int in_cols ){
set_size( in_row, in_cols );
}
void set_size( int in_rows, int in_cols ){
data = new double [ in_rows*in_cols ];
rows = in_rows;
cols = in_cols;
for( int i=0; i<rows*cols; i++ ) data[i]=1.0;
}
Matrix( const Matrix & X );
const Matrix operator=( const Matrix& X );
Matrix( const Glue<Matrix,Matrix> & X );
const Matrix & operator=( const Glue<Matrix,Matrix> & X );
Matrix( const Glue< Glue<Matrix,Matrix>, Matrix > & X );
const Matrix & operator=( const Glue< Glue<Matrix,Matrix>, Matrix > & X );
};
template < typename T1, typename T2 >
class Glue {
public:
const T1 & A;
const T2 & B;
Glue( const T1 & in_A, const T2 & in_B ): A(in_A), B(in_B){}
};
Matrix::Matrix( const Glue<Matrix,Matrix> & X ){
operator=(X);
}
const Matrix & Matrix::operator=( const Glue< Glue<Matrix,Matrix>, Matrix> & X ){
const Matrix & A = X.A.A;
const Matrix & B = X.A.B;
const Matrix & C = X.B;
set_size( A.rows, A.cols );
for( int i=0; i<A.rows * A.cols; i++ ){
data[i] = A.data[i] + B.data[i] + C.data[i];
}
return *this;
}
const Matrix & Matrix::operator=( const Glue<Matrix,Matrix> & X ){
const Matrix & A = X.A;
const Matrix & B = X.B;
set_size( A.rows, A.cols );
for( int i=0; i<A.rows * A.cols; i++ ){
data[i] = A.data[i] + B.data[i];
}
return *this;
}
const Glue<Matrix,Matrix> operator+( const Matrix & A, const Matrix & B ){
return Glue<Matrix, Matrix>(A,B);
}
const Glue< Glue<Matrix,Matrix> ,Matrix> operator+( const Glue<Matrix, Matrix> & P, const Matrix & Q ){
return Glue< Glue<Matrix,Matrix>, Matrix >(P,Q);
}
int main(){
Matrix A1(3,4);
Matrix B1(3,4);
Matrix C1(3,4);
Matrix X(3,4);
X = A1 + B1;
X = A1 + B1 + C1;
for( int i=0; i<X.rows*X.cols; i++ ) std::cout << X.data[i] << std::endl;
return 0;}
0 件のコメント:
コメントを投稿