title: Arithmetic operations on vectors
body: <p>Say I want to provide element-wise arithmetic operations <code>operator+=</code> and <code>operator+</code> for <code>std::vector</code> to add vector entries element by element. Often, I see <code>operator+</code> being implemented in terms of <code>operator+=</code> like so:</p>
  
  <pre><code>#include &lt;algorithm&gt;
  #include &lt;vector&gt;
  
  template&lt;class Type&gt;
  std::vector&lt;Type&gt; &amp; operator+=(std::vector&lt;Type&gt; &amp;x, const std::vector&lt;Type&gt; &amp;y) {
      // Checks for equal size of x and y omitted here...
      std::transform(std::begin(x), std::end(x), std::begin(y), std::begin(x), std::plus&lt;Type&gt;());
      return x;
  }
  
  template&lt;class Type&gt;
  std::vector&lt;Type&gt; operator+(std::vector&lt;Type&gt; x, const std::vector&lt;Type&gt; &amp;y) {
      // Checks for equal size of x and y omitted here...
      return x += y;
  }
  
  int main() {
      std::vector&lt;double&gt; v0{1.0, 2.0, 3.0};
      auto v1 = v0;
  
      auto v2 = v0;
      v2 += v0; // yields [2, 4, 6]
  
      auto v3 = v0 + v1; // yields [2, 4, 6]
  
      return 0;
  }
  </code></pre>
  
  <p>In terms of performance, I guess</p>
  
  <pre><code>template&lt;class Type&gt;
  std::vector&lt;Type&gt; operator+(const std::vector&lt;Type&gt; &amp;x, const std::vector&lt;Type&gt; &amp;y) {
      // Checks for equal size of x and y omitted here...
      std::vector&lt;Type&gt; result;
      result.reserve(x.size());
      std::transform(std::begin(x), std::end(x), std::begin(y), std::back_inserter(result), std::plus&lt;Type&gt;());
      return result;
  }
  </code></pre>
  
  <p>is more efficient because it avoids initializing the copy of the first argument when entering the function but places the result directly into an uninitialized chunk of memory. Is it really worth it to implement the second version or can I assume the compiler to optimize anyway? Also, I consider the second alternative less generic than the first one. Imagine something like</p>
  
  <pre><code>#include &lt;array&gt;
  #include &lt;type_traits&gt;
  
  template&lt;class Container, class Enable = void&gt;
  struct IsSequenceContainer: public std::false_type {
  };
  
  template&lt;&gt;
  template&lt;class Type, std::size_t size&gt;
  struct IsSequenceContainer&lt;std::array&lt;Type, size&gt; &gt;: public std::true_type {
  };
  
  template&lt;&gt;
  template&lt;class Type, class Allocator&gt;
  struct IsSequenceContainer&lt;std::vector&lt;Type, Allocator&gt; &gt;: public std::true_type {
  };
  
  // Use the following operations for std::array and std::vector
  template&lt;class Container&gt;
  typename std::enable_if&lt;IsSequenceContainer&lt;Container&gt;::value, Container&gt;::type operator+(Container x, const Container &amp;y) {
      return x += y;
  }
  </code></pre>