OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Matrix Multiplication with Templated Class [closed]

  • Thread starter Thread starter Aryan MP
  • Start date Start date

Aryan MP

I'm trying to program matrix multiplication with the following class declaration of a matrix:

template<class T, int rows, int cols>
class matrix {
    T m_data[rows * cols];
    int m_rows;
    int m_cols;
    matrix() : m_cols(rows), m_rows(cols) {
        for (int i = 0; i < rows * cols; i++)
            m_data[i] = T(); //default constructor of data type

    matrix(const matrix& other) : m_cols(other.m_cols), m_rows(other.m_rows) {
        for (int i = 0; i < other.size(); i++)
            m_data[i] = other.m_data[i];

    //other functions...

Here is my attempt:

matrix<T, rows, int> operator*(const matrix<T, cols, int>& RHS) const { //error referenced below refers to this line
        if (m_cols != RHS.m_rows) {
            throw std::invalid_argument("Matrix dimensions must match for multiplication!");

        matrix<T, rows, int> toReturn;

        for (int i = 0; i < rows; ++i) {
            for (int j = 0; j < RHS.m_cols; ++j) {
                toReturn(i, j) = 0;
                for (int k = 0; k < cols; ++k) {
                    toReturn(i, j) += (*this)(i, k) * RHS(k, j);

        return toReturn;

The errors I'm getting are: Error C2993 'int': is not a valid type for non-type template parameter 'cols'

In main.cpp, I am attempting to use the function as such:

matrix<int, 2, 2> m1;
m1.set(0, 0, 1);
m1.set(0, 1, 2);
m1.set(1, 0, 3);
m1.set(1, 1, 4);

matrix<int, 2, 1> m2;
m2.set(0, 0, 1);
m2.set(1, 0, 1);

matrix<int, 2, 1> m3 = m1 * m2;

The error I get now is: C2679 binary '*': no operator found which takes a right-hand operand of type 'matrix<int,2,1>' (or there is no acceptable conversion)
Continue reading...

Latest posts

Safwan Aipuram