Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to initialize with multiple return values in c++(0x)
    text
    copied!<p><code>tuple</code> in boost and TR1/c++0x provides a convenient (for the writer of the function) method to return two values from a function--however it seems to damage one major feature of the language for the caller: the ability to simply use the function to initialize a variable:</p> <pre><code>T happy(); const auto meaningful_name(happy()); // RVO means no excess copies </code></pre> <p>but for:</p> <pre><code>tuple&lt;T,U&gt; sad(); </code></pre> <p>we either have to surrender the ability to pick a meaningful name for our return values, and use <code>get&lt;n&gt;()</code> everywhere:</p> <pre><code>const auto two_unrelated_things(sad()); </code></pre> <p>or make a temporary:</p> <pre><code>const auto unwanted_named_temporary(sad()); const auto one_name(get&lt;0&gt;(unwanted_named_temporary)); const auto two_name(get&lt;1&gt;(unwanted_named_temporary)); </code></pre> <p>or switch from initialization to assignment, which only works when the types are assignable, and breaks <code>auto</code>:</p> <pre><code>tuple_element&lt;0, decltype(sad())&gt;::type one_mutable; // there might be a less tuple_element&lt;1, decltype(sad())&gt;::type two_mutable; // verbose way tie(one_mutable,two_mutable) = sad(); </code></pre> <p>or do something unnatural to a local class:</p> <pre><code>const struct ugh { ugh( decltype(sad()) rhs ) : one_name(get&lt;0&gt;(rhs)), two_name(get&lt;1&gt;(rhs)) {} const tuple_element&lt;0, decltype(sad())&gt;::type one_name; const tuple_element&lt;1, decltype(sad())&gt;::type two_name; } stuff(sad()); // at least we avoid the temporary and get initialization </code></pre> <p>Is there a better way? I'm using VC10 compatible constructs above, would anything in full c++0x or boost help? </p> <p>Ideally it would:</p> <ul> <li>allow me to use initialization, not just assignment</li> <li>let the <strong>caller</strong> pick the names for the returned-into variables</li> <li>not make extra copies</li> <li>work for both stack variables and class members</li> <li>possibly be a big crazy template library, but have sane syntax for caller and function writer</li> </ul>
 

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