Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>How about this one? I used <code>std::tuple</code> instead of an <code>initializer_list</code> because the number of tuple arguments are available at compile-time. The <code>tuple_array</code> class below inherits from <code>std::array</code> and adds a templated constructor that is meant to be used with a <code>std::tuple</code>. The contents of the tuple are copied to the underlying array storage using a meta-program <code>Assign</code>, which simply iterates from N down to 0 at compile-time. Finally, the <code>make_tuple_array</code> function accepts arbitrary number of parameters and constructs a <code>tuple_array</code>. The type of the first argument is assumed to be the element type of the array. Good compilers should eliminate the extra copy using RVO. The program works on g++ 4.4.4 and 4.6.1 with RVO.</p> <pre><code>#include &lt;array&gt; #include &lt;tuple&gt; #include &lt;iostream&gt; template &lt;size_t I, typename Array, typename Tuple&gt; struct Assign { static void execute(Array &amp;a, Tuple const &amp; tuple) { a[I] = std::get&lt;I&gt;(tuple); Assign&lt;I-1, Array, Tuple&gt;::execute(a, tuple); } }; template &lt;typename Array, typename Tuple&gt; struct Assign &lt;0, Array, Tuple&gt; { static void execute(Array &amp;a, Tuple const &amp; tuple) { a[0] = std::get&lt;0&gt;(tuple); } }; template &lt;class T, size_t N&gt; class tuple_array : public std::array&lt;T, N&gt; { typedef std::array&lt;T, N&gt; Super; public: template&lt;typename Tuple&gt; tuple_array(Tuple const &amp; tuple) : Super() { Assign&lt;std::tuple_size&lt;Tuple&gt;::value-1, Super, Tuple&gt;::execute(*this, tuple); } }; template &lt;typename... Args&gt; tuple_array&lt;typename std::tuple_element&lt;0, std::tuple&lt;Args...&gt;&gt;::type, sizeof...(Args)&gt; make_tuple_array(Args&amp;&amp;... args) { typedef typename std::tuple_element&lt;0, std::tuple&lt;Args...&gt;&gt;::type ArgType; typedef tuple_array&lt;ArgType, sizeof...(Args)&gt; TupleArray; return TupleArray(std::tuple&lt;Args...&gt;(std::forward&lt;Args&gt;(args)...)); } int main(void) { auto array = make_tuple_array(10, 20, 30, 40, 50); for(size_t i = 0;i &lt; array.size(); ++i) { std::cout &lt;&lt; array[i] &lt;&lt; " "; } std::cout &lt;&lt; std::endl; return 0; } </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