例如:
mat33 operator +(mat33& m1, mat33& m2);
mat33 operator -(mat33& m1, mat33& m2);
mat33 operator +(mat33&& m1, mat33&& m2);
mat33 operator -(mat33&& m1, mat33&& m2);
mat33 operator +(mat33&& m1, mat33& m2);
mat33 operator -(mat33&& m1, mat33& m2);
mat33 operator +(mat33& m1, mat33&& m2);
mat33 operator -(mat33& m1, mat33&& m2);
有无什么方法可以简化这一大串?
If you want to reduce the number of declarations, there is a way, simplifying the code seems impossible. Following the idea of your declaration,
&&,&&
and&&,&
can delegate work to&,&&
. This way the code is not complicated and there is no duplication.At least two implementations are required here, one that moves data and one that does not. Mobile data is divided into lhs and rhs. At the same time, ADL must be taken into consideration. Implementing this requires declaring at least three overloads. Using templates can reduce the declaration to two:
PS: After c++17, you can use constexpr if to implement static branching. Compilers before c++17 can usually complete such optimizations.
Test code:
It’s done. . .
const & can match all references (lvalue, rvalue, constant lvalue, constant rvalue).