Note that there are some explanatory texts on larger screens.

plurals
  1. POconstruction helper make_XYZ allowing RVO and type deduction even if XZY has noncopy constraint
    primarykey
    data
    text
    <p><strong>UPDATE1:</strong> C++17 added type deduction for constructors - which does not imply that the free function is an inferior solution.</p> <p><strong>UPDATE2:</strong> C++17 added guaranteed copy elision (the copy does not even take place conceptually). So with C++17 my code actually works and with optimal performance. But Martinho's code using brace initialisation for the return value is still the cleaner solution I believe. But checkout <a href="https://stackoverflow.com/a/48533239/2712726">this answer from Barry</a> and the comment from T.C.</p> <p><strong>OLD POST:</strong> Type deduction does not work for constructors (at least until and including C++11). The common solution is to rely on RVO (Return Value Optimisation) and write a make_XYZ template function that forwards its parameters to the constructor. An example is <code>std::make_tuple</code>.</p> <p>Any template acrobat who knows a workaround to make this work when nocopy policy is in the way? A valid solution must still allow RVO to happen.</p> <p>Additionally, will the requirement for any make_XYZ disappear with C++14?</p> <pre><code>#include &lt;iostream&gt; template &lt;typename T&gt; struct XYZ { // remove following two lines to make the code compile XYZ (XYZ const &amp; rhs) = delete; XYZ (XYZ &amp;&amp; rhs) = delete; T i; XYZ (T i):i(i) { } }; template &lt;typename T&gt; XYZ&lt;T&gt; make_XYZ (T &amp;&amp; i) { return XYZ&lt;T&gt;(std::forward&lt;T&gt;(i)); } int main () { auto x = make_XYZ(1); std::cout &lt;&lt; x.i &lt;&lt; std::endl; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

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