While implementing expression templates for a vector/array type, I inevitably came to the point where I need to provide operator +=
.
Using the 'default' expression template scheme gives unintuitive results.
The epxression a += b
doesn't return the result of the computation but rather a reference to the left operand which by the means of an operator side effect is increased by the value b
. If operator+=()
now returns an expression template rather than immediately computing the result, a += b;
will have no effect which would probably be rather surprising when using this scheme.
Is there any sophisticated way to handle compound assignment operators and/or side effects in the context of expression templates?
I can think of three possibilites right now:
Use default expression templates and document that the expression template has to be evaluated (by whatever means are provided).
Use special expression templates which have a destructor that performs side-effect computations if necessary.
Provide compound assignment operators that do not use expression templates at all but rather immediately perform side effect computations.
I'm inclined towards using 3 because the other two have their respecitve downsides. While those for 1 are probably rather obvious, 2 has the problem that the construction of the expression template would have to ensure that the actual computation of the expression side effect does not throw if the destructor noexcept shall be maintained. This might in practice be problematic.