Home > Back-end >  Use of class template requires template arguments
Use of class template requires template arguments

Time:12-22

I defined the struct below in C to hold a C class array:

template <int nrow, int ncol>
struct Mat{
    int row_size = nrow;
    int col_size = ncol;
    std::array<std::array<float, ncol>, nrow> mat;
};

Then I tried to define a function which prints this 2D array:

void show(Mat mat){
    for(size_t row=0; row<mat.row_size; row  ){
        for(size_t col=0; col<mat.col_size; col  ){
            std::cout<<mat.mat[row][col]<<" ";
        }
    }
}

However, I get the error below:

Use of class template 'Mat' requires template arguments; argument deduction not allowed in function prototype

I am new to C and I cannot understand what the error means! I thought perhaps trying this might work:

void show(Mat<int, int> mat){
    for(size_t row=0; row<mat.row_size; row  ){
        for(size_t col=0; col<mat.col_size; col  ){
            std::cout<<mat.mat[row][col]<<" ";
        }
    }
}

But then I get another error.

CodePudding user response:

Make your function a template function (the same way you made your template struct) i.e.:

template<int nrow, int ncol>
void show(Mat<nrow, ncol> mat){
    for(size_t row=0; row<mat.row_size; row  ){
        for(size_t col=0; col<mat.col_size; col  ){
            std::cout<<mat.mat[row][col]<<" ";
        }
    }
}

Now you can define your Mat struct as such:

Mat<10,10> matrix;
//insert elements into matrix;
//...
show(mat);

Hope it helps!

  • Related