<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>timburrell.net &#187; Metaprogramming</title>
	<atom:link href="http://timburrell.net/tag/metaprogramming/feed/" rel="self" type="application/rss+xml" />
	<link>http://timburrell.net</link>
	<description>All that is Tim Burrell</description>
	<lastBuildDate>Tue, 28 Sep 2010 01:05:12 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Fun with Variadic Templates: Part II</title>
		<link>http://timburrell.net/blog/2009-02-22/fun-with-variadic-templates-part-ii/</link>
		<comments>http://timburrell.net/blog/2009-02-22/fun-with-variadic-templates-part-ii/#comments</comments>
		<pubDate>Sun, 22 Feb 2009 13:33:57 +0000</pubDate>
		<dc:creator>Tim.</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[C++0x]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Effective C++]]></category>
		<category><![CDATA[Metaprogramming]]></category>

		<guid isPermaLink="false">http://timburrell.net/?p=479</guid>
		<description><![CDATA[<p>As promised in Part I, I think it&#8217;s about time we start to actually have some fun with C++0x&#8217;s variadiac templates.  There&#8217;s lots of basic tutorials out there and people talking about variadics here and there, but I haven&#8217;t seen anyone really delve into yet, so here we go.  First up, the most [...]</p>

<div class="sociable">
<div class="sociable_tagline">
<strong>Share this article:</strong>
</div>

	<a rel="nofollow" target="_blank" href="mailto:?subject=Fun%20with%20Variadic%20Templates%3A%20Part%20II&amp;body=http%3A%2F%2Ftimburrell.net%2Fblog%2F2009-02-22%2Ffun-with-variadic-templates-part-ii%2F" title="E-mail this story to a friend!"><img src="http://timburrell.net/wp-content/plugins/sociable/images/email_link.png" title="E-mail this story to a friend!" alt="E-mail this story to a friend!" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Ftimburrell.net%2Fblog%2F2009-02-22%2Ffun-with-variadic-templates-part-ii%2F&amp;title=Fun%20with%20Variadic%20Templates%3A%20Part%20II" title="Reddit"><img src="http://timburrell.net/wp-content/plugins/sociable/images/reddit.png" title="Reddit" alt="Reddit" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Ftimburrell.net%2Fblog%2F2009-02-22%2Ffun-with-variadic-templates-part-ii%2F&amp;title=Fun%20with%20Variadic%20Templates%3A%20Part%20II" title="StumbleUpon"><img src="http://timburrell.net/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Ftimburrell.net%2Fblog%2F2009-02-22%2Ffun-with-variadic-templates-part-ii%2F&amp;title=Fun%20with%20Variadic%20Templates%3A%20Part%20II" title="Digg"><img src="http://timburrell.net/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://technorati.com/faves?add=http%3A%2F%2Ftimburrell.net%2Fblog%2F2009-02-22%2Ffun-with-variadic-templates-part-ii%2F" title="Technorati"><img src="http://timburrell.net/wp-content/plugins/sociable/images/technorati.png" title="Technorati" alt="Technorati" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://slashdot.org/bookmark.pl?title=Fun%20with%20Variadic%20Templates%3A%20Part%20II&amp;url=http%3A%2F%2Ftimburrell.net%2Fblog%2F2009-02-22%2Ffun-with-variadic-templates-part-ii%2F" title="Slashdot"><img src="http://timburrell.net/wp-content/plugins/sociable/images/slashdot.png" title="Slashdot" alt="Slashdot" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://del.icio.us/post?url=http%3A%2F%2Ftimburrell.net%2Fblog%2F2009-02-22%2Ffun-with-variadic-templates-part-ii%2F&amp;title=Fun%20with%20Variadic%20Templates%3A%20Part%20II" title="del.icio.us"><img src="http://timburrell.net/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.facebook.com/sharer.php?u=http%3A%2F%2Ftimburrell.net%2Fblog%2F2009-02-22%2Ffun-with-variadic-templates-part-ii%2F&amp;t=Fun%20with%20Variadic%20Templates%3A%20Part%20II" title="Facebook"><img src="http://timburrell.net/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Ftimburrell.net%2Fblog%2F2009-02-22%2Ffun-with-variadic-templates-part-ii%2F&amp;title=Fun%20with%20Variadic%20Templates%3A%20Part%20II&amp;source=timburrell.net+All+that+is+Tim+Burrell&amp;summary=As%20promised%20in%20Part%20I%2C%20I%20think%20it%27s%20about%20time%20we%20start%20to%20actually%20have%20some%20fun%20with%20C%2B%2B0x%27s%20variadiac%20templates.%20%20There%27s%20lots%20of%20basic%20tutorials%20out%20there%20and%20people%20talking%20about%20variadics%20here%20and%20there%2C%20but%20I%20haven%27t%20seen%20anyone%20really%20delve%20i" title="LinkedIn"><img src="http://timburrell.net/wp-content/plugins/sociable/images/linkedin.png" title="LinkedIn" alt="LinkedIn" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://twitthis.com/twit?url=http%3A%2F%2Ftimburrell.net%2Fblog%2F2009-02-22%2Ffun-with-variadic-templates-part-ii%2F" title="TwitThis"><img src="http://timburrell.net/wp-content/plugins/sociable/images/twitter.png" title="TwitThis" alt="TwitThis" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.google.com/bookmarks/mark?op=edit&amp;bkmk=http%3A%2F%2Ftimburrell.net%2Fblog%2F2009-02-22%2Ffun-with-variadic-templates-part-ii%2F&amp;title=Fun%20with%20Variadic%20Templates%3A%20Part%20II" title="Google"><img src="http://timburrell.net/wp-content/plugins/sociable/images/googlebookmark.png" title="Google" alt="Google" class="sociable-hovers" /></a>

</div>
<small><em>posted in <a href="http://timburrell.net/topics/blog/">Blog</a> by Tim. <a href="http://timburrell.net/blog/2009-02-22/fun-with-variadic-templates-part-ii/#comments">Comments (1)</a><br />&copy;2012 <a href="http://timburrell.net">timburrell.net</a>. All Rights Reserved.</em></small>]]></description>
			<content:encoded><![CDATA[<p>As promised in <a href="/blog/2009-02-18/fun-with-variadic-templates-part-i/">Part I</a>, I think it&#8217;s about time we start to actually have some fun with C++0x&#8217;s variadiac templates.  There&#8217;s lots of basic tutorials out there and people talking about variadics here and there, but I haven&#8217;t seen anyone really delve into yet, so here we go.  First up, the most trivial but of metaprogramming we can do &#8212; emulating the C++0x <code>sizeof...</code> operator (which yields the number of parameters in a parameter pack):</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code" width="100%"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span>... <span style="color: #007788;">Args</span><span style="color: #000080;">&gt;</span> <span style="color: #0000ff;">struct</span> count<span style="color: #008080;">;</span>
&nbsp;
<span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> T, <span style="color: #0000ff;">typename</span>... <span style="color: #007788;">Args</span><span style="color: #000080;">&gt;</span> <span style="color: #0000ff;">struct</span> count<span style="color: #000080;">&lt;</span>T, Args...<span style="color: #000080;">&gt;</span> <span style="color: #008000;">&#123;</span>
        <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">const</span> <span style="color: #0000ff;">int</span> num <span style="color: #000080;">=</span> count<span style="color: #000080;">&lt;</span>Args...<span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #007788;">num</span> <span style="color: #000040;">+</span> <span style="color: #0000dd;">1</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
&nbsp;
<span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;&gt;</span> <span style="color: #0000ff;">struct</span> count<span style="color: #000080;">&lt;&gt;</span> <span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">const</span> <span style="color: #0000ff;">int</span> num <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
&nbsp;
<span style="color: #666666;">// let's use the struct</span>
<span style="color: #0000ff;">const</span> <span style="color: #0000ff;">int</span> numArgs <span style="color: #000080;">=</span> count<span style="color: #000080;">&lt;</span><span style="color: #0000dd;">1</span>, <span style="color: #0000dd;">2</span>, <span style="color: #0000dd;">3</span>, <span style="color: #0000dd;">4</span>, <span style="color: #0000dd;">5</span>, <span style="color: #0000dd;">6</span>, <span style="color: #0000dd;">7</span>, <span style="color: #0000dd;">8</span>, <span style="color: #0000dd;">9</span>, <span style="color: #0000dd;">10</span><span style="color: #000080;">&gt;</span><span style="color: #008080;">;</span> <span style="color: #666666;">// numArgs will be equal to 10 because there are 10 parameters given to the count struct</span></pre></td></tr></table></div>

<p>Line 1, is pretty much the root of all template metaprogramming trickery.  The fundamentals of it all relies on recursive partial specialization, and line 1 just sets up a forward declaration to the <code>count struct</code>, which never actually gets used.  There&#8217;s some complicated rules to how partial specializations are chosen by a C++ compiler, but the basic rule of thumb is that the most specialized version of the template that applies is what&#8217;s chosen.  So although our instantiation at line 10 could match our blank forward declaration, it doesn&#8217;t.  The meat of our tiny template metaprogram gets called instead: the recursive partial specialization at line 3.</p>
<p>And this partial specialization brings us to the key behind using variadic templates in the real-world.  Since it&#8217;s not possible to do random access on the pack elements, the only choice is to &#8220;unroll&#8221; the packs recursively.  The trick is to define the partial specialization such that the first argument is just a single parameter, and the next is a parameter pack:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> FirstArg, <span style="color: #0000ff;">typename</span>... <span style="color: #007788;">RemainingArgs</span><span style="color: #000080;">&gt;</span> <span style="color: #0000ff;">struct</span> count<span style="color: #000080;">&lt;</span>T, Args...<span style="color: #000080;">&gt;</span><span style="color: #008080;">;</span></pre></div></div>

<p>When the above struct is instantiated with a parameter pack, the first element gets pulled out of the pack into <code>FirstArg</code>, and the remaining parameters are placed in <code>RemainingArgs</code>.  So, if the <code>count struct</code> makes an instantiation of itself with <code>RemainingArgs...</code> as the only instantiation parameter, again the first parameter will get pulled out and become <code>FirstArg</code>, and the rest will get placed in <code>RemainingArgs</code>.  Thus, we can now easily unroll any parameter pack!  </p>
<p>Let&#8217;s go back to the first code listing at line 4.  This is where the recursion happens, and we can see exactly what we were talking about above happening.  The <code>count struct</code> calls itself with the remaining arguments, and simply keeps track of the number of times the recursion happens by incrementing a counter along the way.  When the instantiation finishes <code>count::num</code> will be set to the number of parameters in the parameter pack as of the initial instantiation plus 1.  We add one because technically the recursion only counts the number of items in the parameter pack which, due to our partial specialization, is going to be one less than the number of parameters we pass to <code>count</code> (remember the first element gets picked out of the parameter pack).</p>
<p>The next thing we need to do, like in all forms of recursion, is to define the termination condition of the recursion.  There are a number of ways to do this, but in this first example, we employ the &#8220;empty partial specialization&#8221; trick:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;&gt;</span> <span style="color: #0000ff;">struct</span> count<span style="color: #000080;">&lt;&gt;</span> <span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">const</span> <span style="color: #0000ff;">int</span> num <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></pre></div></div>

<p>This terminates the recursion not because num is implicitly set to zero, but because this specialization does not call itself.  Therefore when the recursion has completely unrolled the parameter pack we hit this empty specialization and since there is no recursive call, nothing else happens.  We only bother to define num here so that if someone explicitly instantiates a <code>count struct</code> with no arguments, they can still call <code>count::num</code> and get a value of zero rather than a compilation error.</p>
<p>Alright, so that was fun, now let&#8217;s look at something a little more complex, and a lot more useful:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
</pre></td><td class="code" width="100%"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">int</span> N, <span style="color: #0000ff;">typename</span>... <span style="color: #007788;">Args</span><span style="color: #000080;">&gt;</span> <span style="color: #0000ff;">struct</span> elementType<span style="color: #008080;">;</span>
&nbsp;
<span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">int</span> N, <span style="color: #0000ff;">typename</span> T, <span style="color: #0000ff;">typename</span>... <span style="color: #007788;">Args</span><span style="color: #000080;">&gt;</span>
<span style="color: #0000ff;">struct</span> elementType<span style="color: #000080;">&lt;</span>N, T, Args...<span style="color: #000080;">&gt;</span> <span style="color: #008000;">&#123;</span>
        static_assert<span style="color: #008000;">&#40;</span>N <span style="color: #000080;">&lt;</span> <span style="color: #0000dd;">sizeof</span>...<span style="color: #008000;">&#40;</span>Args<span style="color: #008000;">&#41;</span> <span style="color: #000040;">+</span> <span style="color: #0000dd;">1</span>, <span style="color: #FF0000;">&quot;overflow!&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        <span style="color: #0000ff;">typedef</span> <span style="color: #0000ff;">typename</span> elementType<span style="color: #000080;">&lt;</span>N <span style="color: #000040;">-</span> <span style="color: #0000dd;">1</span>, Args...<span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #007788;">type</span> type<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
&nbsp;
<span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> T, <span style="color: #0000ff;">typename</span>... <span style="color: #007788;">Args</span><span style="color: #000080;">&gt;</span>
<span style="color: #0000ff;">struct</span> elementType<span style="color: #000080;">&lt;</span><span style="color: #0000dd;">0</span>, T, Args...<span style="color: #000080;">&gt;</span> <span style="color: #008000;">&#123;</span>
        <span style="color: #0000ff;">typedef</span> T type<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
&nbsp;
<span style="color: #666666;">// now let's use our elementType struct</span>
elementType<span style="color: #000080;">&lt;</span><span style="color: #0000dd;">0</span>, <span style="color: #0000ff;">int</span>, <span style="color: #0000ff;">char</span>, std<span style="color: #008080;">::</span><span style="color: #007788;">string</span>, <span style="color: #0000ff;">double</span><span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #007788;">type</span> var0 <span style="color: #000080;">=</span> <span style="color: #0000dd;">1</span><span style="color: #008080;">;</span> <span style="color: #666666;">// var0 is an int</span>
elementType<span style="color: #000080;">&lt;</span><span style="color: #0000dd;">1</span>, <span style="color: #0000ff;">int</span>, <span style="color: #0000ff;">char</span>, std<span style="color: #008080;">::</span><span style="color: #007788;">string</span>, <span style="color: #0000ff;">double</span><span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #007788;">type</span> var1 <span style="color: #000080;">=</span> <span style="color: #FF0000;">'2'</span><span style="color: #008080;">;</span> <span style="color: #666666;">// var1 is a char</span>
elementType<span style="color: #000080;">&lt;</span><span style="color: #0000dd;">2</span>, <span style="color: #0000ff;">int</span>, <span style="color: #0000ff;">char</span>, std<span style="color: #008080;">::</span><span style="color: #007788;">string</span>, <span style="color: #0000ff;">double</span><span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #007788;">type</span> var2 <span style="color: #000080;">=</span> <span style="color: #FF0000;">&quot;;P&quot;</span><span style="color: #008080;">;</span> <span style="color: #666666;">// var2 is a string</span>
elementType<span style="color: #000080;">&lt;</span><span style="color: #0000dd;">3</span>, <span style="color: #0000ff;">int</span>, <span style="color: #0000ff;">char</span>, std<span style="color: #008080;">::</span><span style="color: #007788;">string</span>, <span style="color: #0000ff;">double</span><span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #007788;">type</span> var3 <span style="color: #000080;">=</span> <span style="color:#800080;">3.14159</span><span style="color: #008080;">;</span> <span style="color: #666666;">// var3 is a double</span></pre></td></tr></table></div>

<p>The basic idea behind the <code>elementType struct</code> is that we give the struct an index and a variable number of types, and we can then use the struct&#8217;s <code>type</code> definition as a custom data type that maps back to whatever parameter the index value is associated with.  The above listing at lines 15 through 18 do exactly that.</p>
<p>What&#8217;s so great about that, and why would such a thing be useful?  While it may not seem like such an awesome thing to do at first, what we&#8217;ve done is found a way to pick elements out of a parameter pack by an index.  Essentially we&#8217;ve given ourselves a way to allow random access to packs.  The technique used is similar to the <code>count struct</code>, but not quite the same.  We&#8217;re still using recursion, but this time we need to stop the recursion at the right element.</p>
<p>Take a look at line 6 in the above listing.  This is where all the magic happens.  The <code>elementType struct</code> calls itself using the same variadic unrolling trick that <code>count</code> used, except we decrement N at each step of the way, until N reaches zero, and we hit the termination condition (the partial specialization for when N is zero at lines 9 through 12).  This means if we give an index of 5, we&#8217;ll get 5 recursions and the typedef that ends up getting defined is the one for the 6th parameter in the pack.</p>
<p>No problem right!  So let&#8217;s put all this together for something actually useful &#8212; a variadic tuple class:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code" width="100%"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span>... <span style="color: #007788;">Args</span><span style="color: #000080;">&gt;</span> 
<span style="color: #0000ff;">struct</span> tuple <span style="color: #008000;">&#123;</span>
        tuple<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> Args<span style="color: #000040;">&amp;</span>... <span style="color: #007788;">args</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span><span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
&nbsp;
tuple<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">int</span>, <span style="color: #0000ff;">char</span><span style="color: #000080;">&gt;</span> t1<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">1</span>, <span style="color: #FF0000;">'2'</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></pre></td></tr></table></div>

<p>The idea is we want to be able to use our tuple class like line 6 shows.  This is the example from <a href="/blog/2009-02-18/fun-with-variadic-templates-part-i">Part I</a>, and as I previously mentioned, this isn&#8217;t so useful.  Sure it lets us declare a tuple like we want, but it doesn&#8217;t actually store the tuple&#8217;s constructor arguments, nor does it give us any way to retrieve them.  So how are we going to store the elements?</p>
<p>Like all things variadic, we&#8217;re going to use a recursive template definition!  The tuple class will instantiate itself recursively, storing the arguments as it goes.  Basically the tuple class will become a compile-time linked list of sorts.  This means we&#8217;ll also have to use more metaprogramming to get access to the elements, but for now let&#8217;s take a look at the tuple class definition itself:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
</pre></td><td class="code" width="100%"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span>... <span style="color: #007788;">Args</span><span style="color: #000080;">&gt;</span> <span style="color: #0000ff;">struct</span> tuple<span style="color: #008080;">;</span>
&nbsp;
<span style="color: #666666;">// recursion termination condition</span>
<span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;&gt;</span> <span style="color: #0000ff;">struct</span> tuple<span style="color: #000080;">&lt;&gt;</span> <span style="color: #008000;">&#123;</span><span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
&nbsp;
<span style="color: #666666;">// recursive tuple template</span>
<span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> Head, <span style="color: #0000ff;">typename</span>... <span style="color: #007788;">TailArgs</span><span style="color: #000080;">&gt;</span>
<span style="color: #0000ff;">struct</span> tuple<span style="color: #000080;">&lt;</span>Head, TailArgs...<span style="color: #000080;">&gt;</span> <span style="color: #008080;">:</span> <span style="color: #0000ff;">private</span> tuple<span style="color: #000080;">&lt;</span>TailArgs...<span style="color: #000080;">&gt;</span> <span style="color: #008000;">&#123;</span>
        <span style="color: #ff0000; font-style: italic;">/**
         * \brief  Recursive constructor
        **/</span>
        tuple<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> Head<span style="color: #000040;">&amp;</span> head, <span style="color: #0000ff;">const</span> TailArgs<span style="color: #000040;">&amp;</span>... <span style="color: #007788;">tailArgs</span><span style="color: #008000;">&#41;</span> <span style="color: #008080;">:</span>
                tuple<span style="color: #000080;">&lt;</span>TailArgs...<span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span>tailArgs...<span style="color: #008000;">&#41;</span>,
                mHead<span style="color: #008000;">&#40;</span>head<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">private</span><span style="color: #008080;">:</span>
        Head mHead<span style="color: #008080;">;</span> <span style="color: #666666;">///&lt; Tuple head</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></pre></td></tr></table></div>

<p>Although this might look a bit weird at first, there&#8217;s not actually that much that&#8217;s new here.  We&#8217;re still just recursively defining a template class, and unrolling a parameter pack as we do it, but we&#8217;re doing it via inheritance this time.  The tuple class&#8217; base class is actually itself.  We use the same trick we&#8217;ve used before to extract the first parameter from the parameter pack, but now we pass the template&#8217;s <code>TailArgs</code> to the base class so that the base class&#8217; <code>Head</code> becomes the first element in its super class&#8217; <code>TailArgs</code>.</p>
<p>When the instantiation of this class finishes it will be a tuple class that has an <code>mHead</code> member variable set to the value of the first argument in the parameter pack given to the tuple&#8217;s constructor as the <code>head</code> variable (which you can see being set at line 14).  That tuple class will have a base class that itself has an <code>mHead</code> member variable which is set to be the second parameter in the initial instantiation&#8217;s parameter pack (or the first parameter given to the base class instantiation).  This process repeats until all the parameters in the initial pack are exhausted and the termination condition is hit.</p>
<p>Okay, so that&#8217;s pretty cool, but now what?  Basically we&#8217;ve got this weirdly constructed tuple class with a strange inheritance hierarchy that stores all the elements given to the constructor &#8212; we still need some method for extracting them!  This is where all our previous metaprogramming fun comes into play.  We&#8217;ve already built much of the framework we need to make this happen:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
</pre></td><td class="code" width="100%"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> Head, <span style="color: #0000ff;">typename</span>... <span style="color: #007788;">TailArgs</span><span style="color: #000080;">&gt;</span>
<span style="color: #0000ff;">struct</span> tuple<span style="color: #000080;">&lt;</span>Head, TailArgs...<span style="color: #000080;">&gt;</span> <span style="color: #008080;">:</span> <span style="color: #0000ff;">private</span> tuple<span style="color: #000080;">&lt;</span>TailArgs...<span style="color: #000080;">&gt;</span> <span style="color: #008000;">&#123;</span>
        <span style="color: #ff0000; font-style: italic;">/**
         * \brief  Recursive constructor
        **/</span>
        tuple<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> Head<span style="color: #000040;">&amp;</span> head, <span style="color: #0000ff;">const</span> TailArgs<span style="color: #000040;">&amp;</span>... <span style="color: #007788;">tailArgs</span><span style="color: #008000;">&#41;</span> <span style="color: #008080;">:</span>
                tuple<span style="color: #000080;">&lt;</span>TailArgs...<span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span>tailArgs...<span style="color: #008000;">&#41;</span>,
                mHead<span style="color: #008000;">&#40;</span>head<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #ff0000; font-style: italic;">/**
         * \brief  Get a tuple argument
        **/</span>
        <span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">int</span> N<span style="color: #000080;">&gt;</span>
        <span style="color: #0000ff;">typename</span> elementType<span style="color: #000080;">&lt;</span>N, Head, TailArgs...<span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #007788;">type</span>
        get<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">const</span> <span style="color: #008000;">&#123;</span>
                <span style="color: #0000ff;">return</span> getValueFromTuple<span style="color: #000080;">&lt;</span>N<span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #0000ff;">template</span> getValue<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> elementType<span style="color: #000080;">&lt;</span>N, Head, TailArgs...<span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #007788;">type</span>, Head, TailArgs...<span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #000040;">*</span><span style="color: #0000dd;">this</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #ff0000; font-style: italic;">/**
         * \brief  Get the head value
        **/</span>
        Head                            head<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">const</span> <span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">return</span> mHead<span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #ff0000; font-style: italic;">/**
         * \brief  Get the next argument in the chain
        **/</span>
        <span style="color: #0000ff;">const</span> tuple<span style="color: #000080;">&lt;</span>TailArgs...<span style="color: #000080;">&gt;</span><span style="color: #000040;">&amp;</span>       next<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">const</span> <span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">return</span> <span style="color: #000040;">*</span><span style="color: #0000dd;">this</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">private</span><span style="color: #008080;">:</span>
        Head                            mHead<span style="color: #008080;">;</span>                                  <span style="color: #666666;">///&lt; Tuple head</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
&nbsp;
<span style="color: #666666;">// let's use our new get function!</span>
tuple<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">int</span>, <span style="color: #0000ff;">char</span>, <span style="color: #0000ff;">bool</span>, <span style="color: #0000ff;">double</span><span style="color: #000080;">&gt;</span> t1<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">1</span>, <span style="color: #FF0000;">'2'</span>, <span style="color: #0000ff;">true</span>, <span style="color:#800080;">3.14159</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #0000ff;">char</span> c <span style="color: #000080;">=</span> t1.<span style="color: #007788;">get</span><span style="color: #000080;">&lt;</span><span style="color: #0000dd;">1</span><span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <span style="color: #666666;">// template get function where the index specified returns that parameter of the tuple class</span></pre></td></tr></table></div>

<p>The first function we&#8217;ve added is the tuple&#8217;s <code>get function</code>, which can be seen being used at line 37.  So how the %@*! does that work anyway?  </p>
<p>Our new class member template function works pretty much the same as <a href="http://www.boost.org/doc/libs/1_38_0/libs/tuple/doc/tuple_users_guide.html">Boost&#8217;s tuple library</a> (although much simpler).  All we&#8217;ve done is defined a template function that takes an integer as a template parameter, and we&#8217;ve used our <code>elementType struct</code>, which we&#8217;ve already seen from earlier in the article, to set the return type of the function to whatever type is at that index in the tuple&#8217;s parameter pack!</p>
<p>We are missing some pretty important code though.  The <code>get function</code> then calls the <code>getValue function</code>, which we&#8217;ve yet to define:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
</pre></td><td class="code" width="100%"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">int</span> N<span style="color: #000080;">&gt;</span>
<span style="color: #0000ff;">struct</span> getValueFromTuple <span style="color: #008000;">&#123;</span>
        <span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> ReturnType, <span style="color: #0000ff;">typename</span> Head, <span style="color: #0000ff;">typename</span>... <span style="color: #007788;">TailArgs</span><span style="color: #000080;">&gt;</span>
        <span style="color: #0000ff;">static</span> ReturnType getValue<span style="color: #008000;">&#40;</span>tuple<span style="color: #000080;">&lt;</span>Head, TailArgs...<span style="color: #000080;">&gt;</span><span style="color: #000040;">&amp;</span> t<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>                                                                          
                <span style="color: #0000ff;">return</span> getValueFromTuple<span style="color: #000080;">&lt;</span>N <span style="color: #000040;">-</span> <span style="color: #0000dd;">1</span><span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #0000ff;">template</span> getValue<span style="color: #000080;">&lt;</span>ReturnType, TailArgs...<span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span>t.<span style="color: #007788;">next</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        <span style="color: #008000;">&#125;</span>                                                                          
&nbsp;
        <span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> ReturnType, <span style="color: #0000ff;">typename</span> Head, <span style="color: #0000ff;">typename</span>... <span style="color: #007788;">TailArgs</span><span style="color: #000080;">&gt;</span>
        <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">const</span> ReturnType getValue<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> tuple<span style="color: #000080;">&lt;</span>Head, TailArgs...<span style="color: #000080;">&gt;</span><span style="color: #000040;">&amp;</span> t<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>                                                                          
                <span style="color: #0000ff;">return</span> getValueFromTuple<span style="color: #000080;">&lt;</span>N <span style="color: #000040;">-</span> <span style="color: #0000dd;">1</span><span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #0000ff;">template</span> getValue<span style="color: #000080;">&lt;</span>ReturnType, TailArgs...<span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span>t.<span style="color: #007788;">next</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        <span style="color: #008000;">&#125;</span>                                                                          
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>                                                                           
&nbsp;
<span style="color: #666666;">// termination condition for when getValueFromTuple is instantiated with zero</span>
<span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;&gt;</span>
<span style="color: #0000ff;">struct</span> getValueFromTuple<span style="color: #000080;">&lt;</span><span style="color: #0000dd;">0</span><span style="color: #000080;">&gt;</span> <span style="color: #008000;">&#123;</span>
        <span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> ReturnType, <span style="color: #0000ff;">typename</span>... <span style="color: #007788;">Args</span><span style="color: #000080;">&gt;</span>
        <span style="color: #0000ff;">static</span> ReturnType getValue<span style="color: #008000;">&#40;</span>tuple<span style="color: #000080;">&lt;</span>Args...<span style="color: #000080;">&gt;</span><span style="color: #000040;">&amp;</span> t<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>                                                                         
                <span style="color: #0000ff;">return</span> t.<span style="color: #007788;">head</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        <span style="color: #008000;">&#125;</span>                                                                         
&nbsp;
        <span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> ReturnType, <span style="color: #0000ff;">typename</span>... <span style="color: #007788;">Args</span><span style="color: #000080;">&gt;</span>
        <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">const</span> ReturnType getValue<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> tuple<span style="color: #000080;">&lt;</span>Args...<span style="color: #000080;">&gt;</span><span style="color: #000040;">&amp;</span> t<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>                                                                         
                <span style="color: #0000ff;">return</span> t.<span style="color: #007788;">head</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        <span style="color: #008000;">&#125;</span>                                                                         
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></pre></td></tr></table></div>

<p>This might look a bit complicated, but there&#8217;s absolutely nothing here we haven&#8217;t seen before.  We define a template struct called getValueFromTuple that takes an integer as a template parameter.  This is done so that we can partially specialize the struct so we have a termination condition for the function we actually need (<code>getValue</code>).  C++ function templates are a bit more limited than class templates in how we can partially specialize them &#8212; specific specializations by constants are not allowed, so we use this struct wrapping trick to give us what we need.</p>
<p>The <code>getValue function</code> is also nothing new.  It does the exact same recursive unrolling that the <code>elementType struct</code> uses to extract a specific parameter by index.  The function recursively instantiates itself until N reaches zero and the termination condition is called.  The trick here is that <code>getValue</code> calls the tuple class&#8217; <code>next() function</code> during each instantiation, which passes the tuple&#8217;s base class to the next instantiation of the function.  All we&#8217;re doing here is walking the &#8220;list&#8221; of parameters passed to the tuple&#8217;s constructor, we just happen to be doing it by walking the class hierarchy.</p>
<p>Let&#8217;s take a quick look at the tuple&#8217;s <code>next() function</code> to see how this works:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">const</span> tuple<span style="color: #000080;">&lt;</span>TailArgs...<span style="color: #000080;">&gt;</span><span style="color: #000040;">&amp;</span>       next<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">const</span> <span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">return</span> <span style="color: #000040;">*</span><span style="color: #0000dd;">this</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span></pre></div></div>

<p>This is how we trick the compiler into returning its base class &#8212; which has an <code>mHead</code> that contains the next parameter in the pack.  The return type is the same type that the base class has, so when we return ourselves through the <code>this pointer</code> the compiler does the right thing and casts down to the base class.</p>
<p>So there we go: a fully functioning variadic tuple class that stores its constructor parameters and gives us a way to get at them by their index!  We can now do this:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;">tuple<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">int</span>, <span style="color: #0000ff;">char</span>, string, <span style="color: #0000ff;">double</span><span style="color: #000080;">&gt;</span> t1<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">1</span>, <span style="color: #FF0000;">'2'</span>, <span style="color: #FF0000;">&quot;variadics rule&quot;</span>, <span style="color:#800080;">3.14159</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
<span style="color: #0000ff;">int</span>    var0 <span style="color: #000080;">=</span> t1.<span style="color: #007788;">get</span><span style="color: #000080;">&lt;</span><span style="color: #0000dd;">0</span><span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <span style="color: #666666;">// var0 is now 1</span>
<span style="color: #0000ff;">char</span>   var1 <span style="color: #000080;">=</span> t1.<span style="color: #007788;">get</span><span style="color: #000080;">&lt;</span><span style="color: #0000dd;">1</span><span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <span style="color: #666666;">// var1 is '2'</span>
string var2 <span style="color: #000080;">=</span> t1.<span style="color: #007788;">get</span><span style="color: #000080;">&lt;</span><span style="color: #0000dd;">2</span><span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <span style="color: #666666;">// var2 is now &quot;variadics rule&quot;</span>
<span style="color: #0000ff;">double</span> var3 <span style="color: #000080;">=</span> t1.<span style="color: #007788;">get</span><span style="color: #000080;">&lt;</span><span style="color: #0000dd;">3</span><span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <span style="color: #666666;">// var3 is now 3.14159</span></pre></div></div>

<p>Sweet!  Of course there are many improvements that could be made such as allowing access to elements by reference (for efficiently storing and retrieving large structures), adding iterators, copy constructors, operator overrides, etc, but I&#8217;ll leave that stuff as reader exercises <img src='http://timburrell.net/smilies/yahoo_smiley.gif' alt='&#58;&#41;' class='wp-smiley' width='18' height='18' title='&#58;&#41;' />.</p>
<p>For the next installment the plan is to go even deeper down the the metaprogramming hole, and see what kind of compile-time fun we can have.  Template metaprogramming is a really useful skill to have; the more you can do at compile time, the fewer instructions need to get executed at runtime, plus, as we&#8217;ve just seen in this article, metaprogramming trickery can make other code more readable and, in turn, easier to maintain.  Not only that but playing around with template metaprogramming is a great way to get to know your compiler, and the C++ language!</p>
]]></content:encoded>
			<wfw:commentRss>http://timburrell.net/blog/2009-02-22/fun-with-variadic-templates-part-ii/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

