Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can i make a templated constructor allowing all of l-value ref, r-value ref and initializer_list?
    primarykey
    data
    text
    <p>I'm trying to design a class which has two vectors of large sequences.</p> <pre><code>std::vector&lt;double&gt; factory() { return std::vector&lt;double&gt;{1,2,3}; // it actually generates a large sequence of double } struct my_class { my_class(const std::vector&lt;double&gt;&amp; x, const std::vector&lt;double&gt;&amp; y) : m_x(x), m_y(y) { } std::vector&lt;double&gt; m_x; std::vector&lt;double&gt; m_y; }; int main() { my_class c(factory(), factory()); my_class c2(factory(), {0.5, 1, 1.5}); } </code></pre> <p>Well, it works well but it doesn't use the move constructor of vector. So i tried to change the constructor to accept r-value references with perfect forwarding.</p> <pre><code>struct my_class { template&lt;typename X, typename Y&gt; my_class(X&amp;&amp; x, Y&amp;&amp; y , typename std::enable_if&lt;std::is_convertible&lt;X, std::vector&lt;double&gt; &gt;::value &amp;&amp; std::is_convertible&lt;Y, std::vector&lt;double&gt; &gt;::value&gt;::type * = 0 ) : m_x(std::forward&lt;X&gt;(x)), m_y(std::forward&lt;Y&gt;(y)) { } std::vector&lt;double&gt; m_x; std::vector&lt;double&gt; m_y; }; </code></pre> <p>And now i got a problem. When i try to construct an instance with an initializer_list, i got an error like this.</p> <pre><code>$ g++ -W -Wall -std=gnu++0x a.cpp a.cpp: In function ‘int main()’: a.cpp:34:32: error: no matching function for call to ‘my_class::my_class(std::vector&lt;double&gt;, &lt;brace-enclosed initializer list&gt;)’ a.cpp:17:18: note: candidate is: my_class::my_class(const my_class&amp;) </code></pre> <p>I thought that <code>std::initializer_list&lt;double&gt;</code> might not be convertible to <code>std::vector&lt;double&gt;</code>, but it actually is convertible and i got the same error when i tried without the enable_if argument. Am I missing something?</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.
 

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