2

I am making a matrix library and I would like to be able to do something like

Matrix<double> = Matrix<int> + Matrix<double>

is this possible?

Here is what I have now:

template<typename T>
Matrix<T>& Matrix<T>::operator+(const Matrix& rhs) {
  if(w != rhs.w || h != rhs.h) {
    printf("\e[31m[ERROR] Arithmetic Error: attempted to add %dx%d matrix to %dx%d matrix\e[0m\n", w, h, rhs.w, rhs.h);
  }
  else {
    for(uint32_t i = 0;i < size;++i) {
      m[i] += rhs.m[i];
    }
  }
  return *this;
}
1
  • operator+ which mutate its operands is strange, it looks more as operator += than operator+. Commented Jun 15, 2020 at 12:21

2 Answers 2

2

You can make operator+ template then it could accept other instantiations of Matrix.

E.g.

template<typename T>
template<typename X>
Matrix<T>& Matrix<T>::operator+(const Matrix<X>& rhs) {
  if(w != rhs.w || h != rhs.h) {
    printf("\e[31m[ERROR] Arithmetic Error: attempted to add %dx%d matrix to %dx%d matrix\e[0m\n", w, h, rhs.w, rhs.h);
  }
  else {
    for(uint32_t i = 0;i < size;++i) {
      m[i] += rhs.m[i];
    }
  }
  return *this;
}

Note that for your current implementation, you have to confirm that the current instantiation is allowed to access members of other instantiations like rhs.w. Different instantiations are considered as different types.

Sign up to request clarification or add additional context in comments.

Comments

0

template free function might solve your issue, something like:

template <typename T1, typename T2>
auto operator+(const Matrix<T1>& lhs, const Matrix<T2>& rhs)
{
    if (lhs.w != rhs.w || lhs.h != rhs.h) {
        throw std::runtime_error("Incompatible size");
    }
    using T = decltype(std::declval<T1>() + std::declval<T2>());
    Matrix<T> res(lhs.w, lhs.h);

    for (uint32_t i = 0; i != res.size; ++i) {
      res.m[i] = lhs.m[i] + rhs.m[i];
    }
    return res;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.