c++ - 如何简写非交换乘法?
问题描述
是否有在 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++ 中没有办法。
但是,在添加代理类时,可以获得所需的语法:
#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);
}
推荐阅读
- rust - 如何将切片写入文件?
- netlogo - 如何将列表(和其他信息)从父模型全局变量传递到 Netlogo 的 LevelSpace 中的子模型全局变量
- c++ - C++。std::condition_variable 和多个等待线程
- python - 从哪里可以得到pytorch torchvison 中模型的所有方法的详细描述?
- c - C程序在分配变量时停止执行
- javascript - 一个类中具有来自同一变量的值的两个或多个属性是相关的
- java - 如何为图像存储指定外部位置
- c# - Fluent Validation Entity 添加操作验证问题
- mysql - 使用csv文件到mysql
- javascript - React JS 设置状态仅适用于上一项