Owen Kuhn
Owen Kuhn

Reputation: 85

Overloading operator using templates c++

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;
}

Upvotes: 2

Views: 45

Answers (2)

Jarod42
Jarod42

Reputation: 217075

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;
}

Upvotes: 0

songyuanyao
songyuanyao

Reputation: 172864

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.

Upvotes: 2

Related Questions