Is it possible to return some kind of expression, which then can be further used and simplified, instead of a vector itself?
I have a function Vector3<T> f(Vector3<T> const&, Vector3<T> const&); and I apply it in an expression of the form g = f(a1, b1).cwiseProduct(t1) + f(a2, b2).cwiseProduct(t2). I wonder if this can be optimized. It seems to be unnecessary that a vector is created when f returns. It might be more efficient to return an "expression" instead which then can be optimized for the evaluation of g.
Writing up my comment as it might be clearer as an answer. If you return
autorather thanVector3<T>then the expression type is retained.E.g.
Types of
f1&f2:(this on Visual C++, might be a little different on gcc/clang)
Thanks to @Homer512, it should be noted that this approach is risky, in that if temporary objects are created in
f, the use ofautowill effectively return a pointer to a local variable inf, with the local variable going out of scope. In the docs, under "C++11 and the auto keyword", the problematic example given isThe docs further note that the issue can be fixed by calling
eval()on the whole expression; however this is equivalent in our case to returning theVector3<T>, which is what we were trying to avoid.