【问题标题】:Overloading operator using templates c++使用模板c ++重载运算符
【发布时间】:2023-03-03 02:10:01
【问题描述】:

我正在制作一个矩阵库,我希望能够做类似的事情

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

这可能吗?

这是我现在拥有的:

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

【问题讨论】:

  • operator+ 改变其操作数很奇怪,它看起来更像operator += 而不是operator+

标签: c++ templates operator-overloading


【解决方案1】:

您可以制作operator+ 模板,然后它可以接受Matrix 的其他实例化。

例如

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

请注意,对于您当前的实现,您必须确认当前实例化是否允许访问其他实例化的成员,例如 rhs.w。不同的实例化被认为是不同的类型。

【讨论】:

    【解决方案2】:

    模板免费功能可能会解决您的问题,例如:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-03
      相关资源
      最近更新 更多