template<int N, int M> 构造函数实例化

template<int N, int M> constructor instanciation

基本上,我正在编写矩阵 class,但我想用 int[N][M] 个变量实例化它。

我有这个工作(对于 3、3 矩阵):
matrix.h :

class Matrix {
    private:
        unsigned cols, rows;
        int* data;
    public:
        Matrix(unsigned cols, unsigned row);
        Matrix(int mat[3][3]);
}

matrix.cpp :

inline
Matrix::Matrix(unsigned cols, unsigned rows) : cols (cols), rows (rows) {
    if (rows == 0 || cols == 0) {
        throw std::out_of_range("Matrix constructor has 0 size");
    }
    data = new int[rows * cols];
}

Matrix::Matrix(int mat[3][3]) : Matrix(3, 3) {
    for(unsigned row = 0; row < rows; row++) {
        for(unsigned col = 0; col < cols; col++) {
            (*this)(col, row) = mat[col][row];
        }
    }
}

然后我尝试实现一个模板构造函数:

template<int N, int M>
Matrix(int[N][M]) : Matrix(N, M) {
    for(unsigned row = 0; row < rows; row++) {
        for(unsigned col = 0; col < cols; col++) {
            (*this)(col, row) = mat[col][row];
        }
    }
}

这似乎可以编译,但是当我执行测试函数时:

void test() {
    int tab[3][3] = {
        {1,2,3},
        {4,5,6},
        {7,8,9}
    };
    Matrix mat(tab);
}

我收到这个错误:

matrix.cpp:10:19: error: no matching function for call to ‘Matrix::Matrix(int [3][3])’
     Matrix mat(tab);

尽管我是这样模板化的(在 Matrix class 下的 .h 文件中):

template<> Matrix::Matrix<3, 3>(int[3][3]);

我真的需要一些帮助,以及如何使用从 0 到 10 的 int 的每个组合实例化它

几件事...

首先请注意 Matrix(int[N][M]) 不完整,缺少参数名称。另请注意,它等同于 Matrix(int(*)[M]).

其次,数组维度的类型是size_t,而不是int

第三,要传递实际数组而不是指针,您需要通过引用获取数组。

将它们放在一起你的构造函数应该看起来像

template<size_t N, size_t M>
Matrix(int const (&mat)[N][M]) : Matrix(N, M)
{
    for (size_t n = 0; n < N; ++n)
    {
        for (size_t m = 0; m < m; ++m)
        {
            (*this)(n, m) = mat[n][m];
        }
    }
}