I am trying to write a
friend T operator+( lhs, rhs){
};
Now, I would like to avoid construction of temporaries when possible.
For example:
- If both
lhs
andrhs
areconst T&
theoperator+
should create atemp
copy-constructing fromlhs
, thentemp += rhs;
to it and finallyreturn std::move(temp)
. - If
lhs
isT&&
then I want to directly sumrhs
to it as inlhs += rhs;
and thenreturn std::move(lhs)
. This case avoid a copy-construction in(A+B)+C
since the output of(A+B)
is not needed outside the expression. Notice that we might have to dotemp(std::move(lhs))
to have a common code for both Case 1. and Case 2. - Similarly for the other two case when either
rhs
or bothlhs
andrhs
areT&&
.
By writing four overloads I have managed to do this. Now, I have read that it is possible to take advantage of templates and forward
to reduce the number of overloads or maybe even write it in just one template function. I am having trouble understanding how.
It seems to be that I need
template<typename R, typename S, typename T>
R operator+(S&& lhs, T&& rhs){
// ...
};
But what I have tried for the content doesn't work.
There is an additional issue that I might have to deal with. If instead of operator+
we need operator-
or operator/
the body of the method it not necessarily similar in all the cases. In A/B
, if A
is T&&
we can A /= B
. But if B
is the one that is T&&
then we might need to do B.reciprocal() *= A
. So, I think I also need a way to know which case was entered in the template.
Note: My multiplication IS commutative (component-wise multiplication in matrices).
Could you give some comments and ideas on how to approach this problem?
Note to self and to the next reader: A link to some reading on the use of expression templates.