I would like to implement a unary arithmetic operator with move semantic for std::vector. The purpose is to avoid internal allocation inside the operator if it is applied on an rvalue.
The problem: the following operation does not compile: c = -(a + b)
The reason this does not compile is because the binary arithmetic operator + I implemented for std::vector returns a const lvalue (so that the compiler will complain on (a + b) = c, which doesn't make sense).
The binary + operator
template<class T, class AllocVect1, class AllocVect2>
inline const std::vector<T> operator+ (
const std::vector<T, AllocVect1> &v1,
const std::vector<T, AllocVect2> &v2) {
std::vector<T> vout;
*Compute vout = v1 + v2*
return vout;
}
The unary operator
template<class T, class Alloc>
inline const std::vector<T>& operator- (std::vector<T, Alloc> &&v) {
std::transform (
v.begin (),
v.end (),
v.begin (),
[](const auto &val){return -val;});
return v;
}