首页 > 解决方案 > 如何简写非交换乘法?

问题描述

是否有在 C++ 中编写非交换变量乘法的简写?

例如,对于交换变量,我们可以这样做:

a = a * b;
a *= b;    // same as the above

但是对于非交换变量,我们不能:

a = a * b; // #1
a = b * a; // #2 different than above

a *= b;  // same as #1
// ???   // shorthand to #2?

可以简写#2吗?

标签: c++operatorsmultiplication

解决方案


正如评论中所指出的,标准 C++ 中没有办法。

但是,在添加代理类时,可以获得所需的语法:

#include <assert.h>
#include <array>

template <class T>
class R
{
public:
  R(T& lhs)
    : _lhs(lhs)
  {}
  T& operator *=(const T& rhs)
  {
    _lhs = rhs * _lhs;
    return _lhs;
  }
  T& operator -=(const T& rhs)
  {
    _lhs = rhs - _lhs;
    return _lhs;
  }

private:
  T& _lhs;
};

int main()
{
  int a = 2, b = 5;
  R(a) -= b;
  assert(a == 3);
}

演示


推荐阅读