Note that there are some explanatory texts on larger screens.

plurals
  1. POOmit return type in C++11
    text
    copied!<p>I've recently found myself using the following macro with gcc 4.5 in C++11 mode:</p> <pre><code>#define RETURN(x) -&gt; decltype(x) { return x; } </code></pre> <p>And writing functions like this:</p> <pre><code>template &lt;class T&gt; auto f(T&amp;&amp; x) RETURN (( g(h(std::forward&lt;T&gt;(x))) )) </code></pre> <p>I've been doing this to avoid the inconvenience having to effectively write the function body twice, and having keep changes in the body and the return type in sync (which in my opinion is a disaster waiting to happen).</p> <p>The problem is that this technique only works on one line functions. So when I have something like this (convoluted example):</p> <pre><code>template &lt;class T&gt; auto f(T&amp;&amp; x) -&gt; ... { auto y1 = f(x); auto y2 = h(y1, g1(x)); auto y3 = h(y1, g2(x)); if (y1) { ++y3; } return h2(y2, y3); } </code></pre> <p>Then I have to put something horrible in the return type.</p> <p>Furthermore, whenever I update the function, I'll need to change the return type, and if I don't change it correctly, I'll get a compile error if I'm lucky, or a runtime bug in the worse case. Having to copy and paste changes to two locations and keep them in sync I feel is not good practice.</p> <p>And I can't think of a situation where I'd want an implicit cast on return instead of an explicit cast.</p> <p>Surely there is a way to ask the compiler to deduce this information. What is the point of the compiler keeping it a secret? I thought C++11 was designed so such duplication would not be required.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload