Template trick to optimize out allocations
<p>I have:</p>

<pre><code>struct DoubleVec {
  std::vector&lt;double&gt; data;
};

DoubleVec operator+(const DoubleVec&amp; lhs, const DoubleVec&amp; rhs) {
  DoubleVec ans(lhs.size());
  for(int i = 0; i &lt; lhs.size(); ++i) {
    ans[i] = lhs[i]] + rhs[i]; // assume lhs.size() == rhs.size()
  }
  return ans;
}

DoubleVec someFunc(DoubleVec a, DoubleVec b, DoubleVec c, DoubleVec d) {
  DoubleVec ans = a + b + c + d;
}
</code></pre>

<p>Now, in the above, the "a + b + c + d" will cause the creation of 3 temporary DoubleVec's -- is there a way to optimize this away with some type of template magic ... i.e. to optimize it down to something equivalent to:</p>

<pre><code>DoubleVec ans(a.size());
for(int i = 0; i &lt; ans.size(); i++) ans[i] = a[i] + b[i] + c[i] + d[i];
</code></pre>

<p>You can assume all DoubleVec's have the same # of elements.</p>

<p>The high level idea is to have do some type of templateied magic on "+", which "delays the computation" until the =, at which point it looks into itself, goes hmm ... I'm just adding thes numbers, and syntheizes a[i] + b[i] + c[i] + d[i] ... instead of all the temporaries.</p>

<p>Thanks!</p>
