#include /* needed for std::size_t */ #include /* needed for printf */ #include /* needed for assert */ enum class StorageOrder {ColMajor, RowMajor}; template struct Matrix { const std::size_t m; /* number of rows */ const std::size_t n; /* number of columns */ const std::size_t incRow; const std::size_t incCol; T* data; Matrix(std::size_t m, std::size_t n, StorageOrder order) : m(m), n(n), incRow(order == StorageOrder::ColMajor? 1: n), incCol(order == StorageOrder::RowMajor? 1: m), data(new T[m*n]) { } ~Matrix() { delete[] data; } const T& operator()(std::size_t i, std::size_t j) const { assert(i < m && j < n); return data[i*incRow + j*incCol]; } T& operator()(std::size_t i, std::size_t j) { assert(i < m && j < n); return data[i*incRow + j*incCol]; } void print() { for (std::size_t i = 0; i < m; ++i) { std::printf(" "); for (std::size_t j = 0; j < n; ++j) { /* be careful here, printf is not polymorph */ std::printf(" %4.1lf", (double) data[i*incRow + j*incCol]); } std::printf("\n"); } } }; template void init_matrix(Matrix& A) { for (std::size_t i = 0; i < A.m; ++i) { for (std::size_t j = 0; j < A.n; ++j) { A(i, j) = j * A.n + i + 1; } } } int main() { Matrix A(7, 8, StorageOrder::ColMajor); init_matrix(A); std::printf("A =\n"); A.print(); }