template 构造函数实例

问题描述 投票:0回答:1

[基本上,我正在编码一个Matrix类,但是我想用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类下的.h文件中:

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

我真的可以为此提供帮助,以及如何使用int的每个组合(从0到10进行实例化)

c++ templates constructor instantiation
1个回答
0
投票

几件事...

首先注意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];
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.