// matrix.cpp
#include <iostream>
#include <initializer_list>
template <typename T, int N>
class Matrix {
static_assert(N > 0, "");
public:
//------------------------------------------
//
// 挿入演算子
//
//------------------------------------------
friend std::ostream& operator <<(std::ostream& os, const Matrix& x) {
os << "[";
for (int iRow = 0; iRow < N; iRow++) {
os << "[";
for (int iColumn = 0; iColumn < N; iColumn++) {
os << x.elements_[iRow][iColumn];
if (iColumn != N - 1)
os << ",";
}
os << "]";
if (iRow != N - 1)
os << ",";
}
os << "]";
return os;
}
public:
//------------------------------------------
//
// コンストラクタ、デストラクタ、コピー、ムーブ
//
//------------------------------------------
Matrix() noexcept(noexcept(T())) {}
Matrix(const T& a) {
for (int i = 0; i < N; i++)
elements_[i][i] = a;
}
Matrix(std::initializer_list<std::initializer_list<T>> ll) {
auto itRow = ll.begin();
for (int iRow = 0; iRow < N && itRow != ll.end(); iRow++, ++itRow) {
auto l = *itRow;
auto itColumn = l.begin();
for (int iColumn = 0; iColumn < N && itColumn != l.end(); iColumn++, ++itColumn) {
elements_[iRow][iColumn] = *itColumn;
}
}
}
Matrix(const Matrix& other) noexcept = default;
Matrix(Matrix&&) noexcept = default;
~Matrix() = default;
Matrix& operator =(const Matrix&) & noexcept = default;
Matrix& operator =(Matrix&&) & noexcept = default;
Matrix&& operator =(const Matrix&) && noexcept = delete;
Matrix&& operator =(Matrix&&) && noexcept = delete;
protected:
T elements_[N][N] = {};
}; // class Matrix
int main()
{
Matrix<int, 3> x{{1,2,3},{4,5,6},{7,8,9}};
Matrix<int, 3> y;
y = x;
std::cout << x << std::endl;
std::cout << y << std::endl;
//Matrix<int, 3>() = x;
//Matrix<int, 3>() = Matrix<int, 3>();
return 0;
}
実行結果は
[[1,2,3],[4,5,6],[7,8,9]]
[[1,2,3],[4,5,6],[7,8,9]]
のようになる。
Matrix(const T& a)で、要素型から行列に容易に変換できるようにした。
initializer_listを使って初期化ができるようにした。
また、一時オブジェクトへの代入を禁止した(65-66行目)。
次回は、要素にアクセスするためのoperator()と算術単項演算子を定義してみたい。
0 件のコメント :
コメントを投稿