title: Why can't we have automatically deduced return types?
body: <p>Recently I was working a friend who wanted to make C++ more Haskell-y, and we wanted a function that's basically like this:</p>
  
  <pre><code>auto sum(auto a, auto b) {
      return a + b;
  }
  </code></pre>
  
  <p>Apparently I can't use auto as a parameter type, so I changed it to this:</p>
  
  <pre><code>template&lt;class A, class B&gt;
  auto sum(A a, B b) {
      return a + b;
  }
  </code></pre>
  
  <p>But that doesn't work either. What we eventually realized we need this:</p>
  
  <pre><code>template&lt;class A, class B&gt;
  auto sum(A a, B b) -&gt; decltype(a + b) {
      return a + b;
  }
  </code></pre>
  
  <p>So my question is, what's the point? Isn't <code>decltype</code> just repeating information, since the compiler can just look at the return statement?</p>
  
  <p>I considered that maybe it's needed so we can just include a header file:</p>
  
  <pre><code>template&lt;class A, class B&gt;
  auto sum(A a, B b) -&gt; decltype(a + b);
  </code></pre>
  
  <p>... but we can't use templates like that anyway.</p>
  
  <p>The other thing I considered was that it might be easier for the compiler, but it seems like it would actually be harder.</p>
  
  <p>Case 1: With <code>decltype</code></p>
  
  <ul>
  <li>Figure out the type of the <code>decltype</code> statement</li>
  <li>Figure out the types of any return values</li>
  <li>See if they match</li>
  </ul>
  
  <p>Case 2: Without <code>decltype</code></p>
  
  <ul>
  <li>Figure out the types of any return values</li>
  <li>See if they match</li>
  </ul>
  
  <p>So with those things in mind, what's the point of the trailing return type with <code>decltype</code>?</p>