title: std::begin and R-values
body: <p>Recently I was trying to fix a pretty difficult const-correctness compiler error.  It initially manifested as a multi-paragraph template vomit error deep within Boost.Python.</p>
  
  <p>But that's irrelevant: it all boiled down to the following fact: the C++11 <code>std::begin</code> and <code>std::end</code> iterator functions are not overloaded to take R-values.</p>
  
  <p>The definition(s) of <code>std::begin</code> are:</p>
  
  <pre><code>template&lt; class C &gt;
  auto begin( C&amp; c ) -&gt; decltype(c.begin());
  
  template&lt; class C &gt;
  auto begin( const C&amp; c ) -&gt; decltype(c.begin());
  </code></pre>
  
  <p>So since there is no R-value/Universal Reference overload, if you pass it an R-value you get a const iterator.</p>
  
  <p>So why do I care?  Well, if you ever have some kind of "range" container type, i.e. like a "view", "proxy" or a "slice" or some container type that presents a sub iterator range of another container, it is often very convenient to use R-value semantics and get non-const iterators from temporary slice/range objects.  But with <code>std::begin</code>, you're out of luck because <code>std::begin</code> will always return a const-iterator for R-values.  This is an old problem which C++03 programmers were often frustrated with back in the day before C++11 gave us R-values - i.e. the problem of temporaries always binding as <code>const</code>.</p>
  
  <p>So, why isn't <code>std::begin</code> defined as:</p>
  
  <pre><code>template &lt;class C&gt;
  auto begin(C&amp;&amp; c) -&gt; decltype(c.begin());
  </code></pre>
  
  <p>This way, if <code>c</code> is constant we get a <code>C::const_iterator</code> and a <code>C::iterator</code> otherwise. </p>
  
  <p>At first, I thought the reason was for safety.  If you passed a temporary to <code>std::begin</code>, like so:</p>
  
  <pre><code>auto it = std::begin(std::string("temporary string")); // never do this
  </code></pre>
  
  <p>...you'd get an invalid iterator.  But then I realized this problem still exists with the current implementation.  The above code would simply return an invalid <em>const</em>-iterator, which would probably segfault when dereferenced.</p>
  
  <p>So, why is <code>std::begin</code> <em>not</em> defined to take an R-value (or more accurately, a <a href="http://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers" rel="noreferrer"><strong>Universal Reference</strong></a>)?  Why have two overloads (one for <code>const</code> and one for <code>non-const</code>)?</p>