Help with Template Class!

I'm learning template functions and template classes so I'm trying to do a Matrix class to do some operations like insertion/sum/invertible..etc and I came up with this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  #include <iostream>
#define SIZE 3

template<class T, int I = SIZE, int J = SIZE>
class Matrix{
  T matrix[I][J];
  
  public:
       
    T Get_Matrix(int i, int j){
      return matrix[i][j];
    }
    
    void Set_Matrix(){
      T value;
      for(int i = 0; i < I; i++){
        for(int j = 0; j < J; j++){
          std::cin>>value;
          matrix[i][j] = value;
        } 
      }   
    } 
    
    void Print_Matrix(){
      for(int i = 0; i< I; i++){
        for(int j = 0; j< J; j++)
          std::cout<<matrix[i][j];
        std::cout<<std::endl;
      }
    } 
};


the way it's right now works but I'm trying to do the SUM method but I'm getting a hard time! I'm trying something like this:

1
2
3
4
5
6
7
T Sum(T M1[][J], T M2[][J]){
  for(int i = 0; i < I; i++){
    for(int j = 0; j < J; j++)
      M1[i][j] = M1[i][j] + M2[i][j];
  }
  return M1[0][0];
}


The problem is the syntax while I'm at the main function:

1
2
3
4
5
6
7
8
9
10
11
int main(){
  Matrix<int> matrix1, matrix2;
  
  matrix1.Set_Matrix();  //works
  matrix2.Set_Matrix();  //works

 /*now that I have a function returning something, how I'll do it?*/
 matrix1.Sum(matrix1, matrix2);  //error
 matrix1 = Sum(matrix1, matrix2); //error
 matrix1 = matrix.Sum(matrix1, matrix2); //error
}


I know that my method will return just the first position of the new matrix with the previous sum, I can correct it with a loop but first I need to know how to call it properly :\

Also, do you think my class is well written? I also need to know how to improve myself :)

Thnak you!
Last edited on
Lets presume that you have declaration:
1
2
template <class T>
T Sum( T M1[][J], T M2[][J] );

And you call a function
1
2
Matrix<int> matrix1, matrix2;
Sum( matrix1, matrix2 );

The parameter types have many possibilities, but lets look at some
1
2
3
Sum( Matrix<int>, Matrix<int> ); // No, template requires 2D arrays
Sum( int[][J], int[][J] ); // No, Matrix<int> is not int
Sum( Matrix<int>[][J], Matrix<int>[][J] ); // No, parameters were not arrays 

You should use either matrices or arrays, consistently.

Your compiler must say something about each error. Some of it should give hints.
So, what's the correct way?, I already saw that I need to use <int> inside the parameter too, I would go with

Sum(Matrix<int>[][J], Matrix2<int>[][J]); but you mentioned that this is wrong too :\
Topic archived. No new replies allowed.