Note that there are some explanatory texts on larger screens.

plurals
  1. POfunction overloading with a lot of arguments
    primarykey
    data
    text
    <p>Say I have this constructor in C++:</p> <pre><code> A::A( std::string const&amp; name, std::string const&amp; type, std::vector&lt;B&gt; const&amp; b_vec, bool unique ) : _name(name), _type(type), _b_vec(b_vec), _unique(unique) { }; </code></pre> <p>I would like to overload this constructor for the case where the arguments are rvalues (I want to use move semantics there).</p> <pre><code> A::A( std::string &amp;&amp; name, std::string &amp;&amp; type, std::vector&lt;B&gt; &amp;&amp; b_vec, bool unique ) : _name(name), _type(type), _b_vec(b_vec), _unique(unique) { }; </code></pre> <p>The above one works fine when all of the arguments are rvalues, but suppose if only some of them are is in the next example:</p> <pre><code> // create some lvalues somehow std::string name = "stack overflow"; std::vector&lt;B&gt; vec = { ... }; // implementation of B's constructot is not important // call a mixed constructor A new_A_instance(name, "cool-website", vec, true); </code></pre> <p>it is to my understanding that since 'const&amp;' cannot bind to '&amp;&amp;' but '&amp;&amp;' can bind to 'const&amp;' the first (non-move) constructor would be used. </p> <p>This seems sub-optimal, since two of the four arguments could be moved (because they are rvalue) instead of being copied (as is the case in the first constructor).</p> <p>So I could overload the operator for this specific case, but one could easily image a case where other arguments are rvalue and others are agin lvalue. Should I overload the constructor for each of these cases? This would combinatorily lead to very much overloads as the number of arguments increases...</p> <p>I kind-of <em>feel</em> there is a better solution (perhaps using templates, but my template knowledge is shamefully low).</p> <p>Note: this problem isn't tied to overloading pass-by-ref functions to move functions per-se, but I found this a good example (especially since the overloads don't <em>feel</em> very different). Also note that I just used constructors as an example, but the overloaded function can be anything.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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