通过使用标量参数覆盖运算符来修改类成员

时间:2018-06-28 16:10:44

标签: c++ templates operator-overloading

我正在编写一个以std::vector作为成员的类,并且我希望能够通过使用默认操作符+ / +=,{以标量为参数的{1}} / *等,例如

*=

我想将运算符重载定义为:

MyClass<float> obj;
obj += 4.0;

我没有编译或运行时错误,但值保持不变。我尝试了多种不同类型的返回值(template <class _type> matrix2D<_type>& matrix2D<_type>::operator=(matrix2D<_type> _mat){ std::swap(_mat,*this); return *this; }; template <class _type> template <typename _input_type> myClass<_type> myClass<_type>::operator*(_input_type _val) { for (int i = 0; i < data.size(); ++i) data[i] *= _val; return *this; }; template <class _type> template <typename _input_type> myClass<_type> myClass<_type>::operator*=(_input_type _val) { for (int i = 0; i < data.size(); ++i) data[i] *= _val; return *this; }; MyClass&)并传递了一个void对象作为参数。我想念什么?

1 个答案:

答案 0 :(得分:0)

不要天真地写y,否则它将成为世界上最慢的实现。绝对不要使用std::val_array,因为它没有使用我所知道的任何编译器进行优化。凭空想像,它死在水里了。我的博士学位论文中有一个Matrix类,如果您愿意的话,可以从那里得到启发:https://github.com/kvahed/codeare/blob/master/src/matrix/Matrix.hpp

根据经验,请坚持使用std::vector,并使用<algorithm>中的功能,例如std::accumulatestd::transform,...。并且始终实现运算符,并在其他任何地方使用它。

因此例如涵盖标量和矩阵元素的乘法:

template <typename T>
class Matrix {
  public:
  ...
  Matrix<T>& operator*=(const T& t) {
    if (t != T(1)) {
      std::transform(
        v_.begin(), v_.end(), v_.begin(), std::bind2nd(std::multiplies<T>(), t));
    }
    return *this;
  }
  Matrix<T>& operator*=(const Matrix<T>& m) {
    std::transform(
      v_.begin(), v_.end(), m.begin(), v_.begin(), std::multiplies<T>()));
    return *this;
  }
  template<typename S>
  Matrix<T> operator* (const S& s) {
    return *this *= s;
  }
  ...
  private:
    std::vector<T> v_;
}

但是这忽略了您的CPU将能够执行的SIMD指令集: https://github.com/kvahed/codeare/blob/master/src/matrix/SIMDTraits.hpp

但是您应该记住一些事实,这些事实并非无关紧要。特别是,当矩阵没有分配到堆上时,内存可能会不对齐。这将完全杀死您。手工计算会更快。 https://github.com/kvahed/codeare/blob/master/src/matrix/Allocator.hpp

认真地,正确地构建您想要的东西需要大量的工作和测试代码。

TLDR:如果您正在寻找幼稚的实现,请使用<algorithm>远离val_array。随意使用我的东西。如果您有问题,随时可以。