Note that there are some explanatory texts on larger screens.

plurals
  1. POmin and perfect forwarding
    text
    copied!<p>The min algorithm is normally expressed like this:</p> <pre><code>template &lt;typename T&gt; const T&amp; min(const T&amp; x, const T&amp; y) { return y &lt; x ? y : x; } </code></pre> <p>However, this does not allow constructs of the form <code>min(a, b) = 0</code>. You can achieve that with an additional overload:</p> <pre><code>template &lt;typename T&gt; T&amp; min(T&amp; x, T&amp; y) { return y &lt; x ? y : x; } </code></pre> <p>What I would like to do is unify these two overloads via perfect forwarding:</p> <pre><code>template &lt;typename T&gt; T&amp;&amp; min(T&amp;&amp; x, T&amp;&amp; y) { return y &lt; x ? std::forward&lt;T&gt;(y) : std::forward&lt;T&gt;(x); } </code></pre> <p>However, g++ 4.5.0 spits out a warning for <code>min(2, 4)</code> that I return a reference to a temporary. Did I do something wrong?</p> <hr> <p>Okay, I get it. The problem is with the conditional operator. In my first solution, if I call <code>min(2, 4)</code> the conditional operator sees an xvalue and thus moves from the forwarded <code>x</code> to produce a temporary object. Of course it would be dangerous to return that by reference! If I forward the whole expression instead of <code>x</code> and <code>y</code> seperately, the compiler does not complain anymore:</p> <pre><code>template &lt;typename T&gt; T&amp;&amp; min(T&amp;&amp; x, T&amp;&amp; y) { return std::forward&lt;T&gt;(y &lt; x ? y : x); } </code></pre> <hr> <p>Okay, I got rid of the references for arithmetic types :)</p> <pre><code>#include &lt;type_traits&gt; template &lt;typename T&gt; typename std::enable_if&lt;std::is_arithmetic&lt;T&gt;::value, T&gt;::type min(T x, T y) { return y &lt; x ? y : x; } template &lt;typename T&gt; typename std::enable_if&lt;!std::is_arithmetic&lt;T&gt;::value, T&amp;&amp;&gt;::type min(T&amp;&amp; x, T&amp;&amp; y) { return std::forward&lt;T&gt;(y &lt; x ? y : x); } </code></pre>
 

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