<?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; Programming</title>
	<atom:link href="http://timburrell.net/tag/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://timburrell.net</link>
	<description>All that is Tim Burrell</description>
	<lastBuildDate>Sun, 04 Jul 2010 01:44:20 +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;2010 <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>
		<item>
		<title>Fun with Variadic Templates: Part I</title>
		<link>http://timburrell.net/blog/2009-02-18/fun-with-variadic-templates-part-i/</link>
		<comments>http://timburrell.net/blog/2009-02-18/fun-with-variadic-templates-part-i/#comments</comments>
		<pubDate>Wed, 18 Feb 2009 23:15:35 +0000</pubDate>
		<dc:creator>Tim.</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C++0x]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Effective C++]]></category>

		<guid isPermaLink="false">http://timburrell.net/?p=371</guid>
		<description><![CDATA[<p>If you&#8217;re a C++ user, you&#8217;ve probably heard that the up and coming language revision, C++0x, is adding support for variadic templates.  And if you&#8217;re anything like me, perhaps your first question was &#8220;Cool, so what good are they?&#8221;  And I would say &#8220;Excellent question!&#8221; to such an inquiry, because C++ has been [...]</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%20I&amp;body=http%3A%2F%2Ftimburrell.net%2Fblog%2F2009-02-18%2Ffun-with-variadic-templates-part-i%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-18%2Ffun-with-variadic-templates-part-i%2F&amp;title=Fun%20with%20Variadic%20Templates%3A%20Part%20I" 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-18%2Ffun-with-variadic-templates-part-i%2F&amp;title=Fun%20with%20Variadic%20Templates%3A%20Part%20I" 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-18%2Ffun-with-variadic-templates-part-i%2F&amp;title=Fun%20with%20Variadic%20Templates%3A%20Part%20I" 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-18%2Ffun-with-variadic-templates-part-i%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%20I&amp;url=http%3A%2F%2Ftimburrell.net%2Fblog%2F2009-02-18%2Ffun-with-variadic-templates-part-i%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-18%2Ffun-with-variadic-templates-part-i%2F&amp;title=Fun%20with%20Variadic%20Templates%3A%20Part%20I" 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-18%2Ffun-with-variadic-templates-part-i%2F&amp;t=Fun%20with%20Variadic%20Templates%3A%20Part%20I" 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-18%2Ffun-with-variadic-templates-part-i%2F&amp;title=Fun%20with%20Variadic%20Templates%3A%20Part%20I&amp;source=timburrell.net+All+that+is+Tim+Burrell&amp;summary=If%20you%27re%20a%20C%2B%2B%20user%2C%20you%27ve%20probably%20heard%20that%20the%20up%20and%20coming%20language%20revision%2C%20C%2B%2B0x%2C%20is%20adding%20support%20for%20variadic%20templates.%20%20And%20if%20you%27re%20anything%20like%20me%2C%20perhaps%20your%20first%20question%20was%20%22Cool%2C%20so%20what%20good%20are%20they%3F%22%20%20And%20I%20would%20say%20%22E" 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-18%2Ffun-with-variadic-templates-part-i%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-18%2Ffun-with-variadic-templates-part-i%2F&amp;title=Fun%20with%20Variadic%20Templates%3A%20Part%20I" 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-18/fun-with-variadic-templates-part-i/#comments">Leave a Comment</a><br />&copy;2010 <a href="http://timburrell.net">timburrell.net</a>. All Rights Reserved.</em></small>]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re a C++ user, you&#8217;ve probably heard that the up and coming language revision, C++0x, is adding support for variadic templates.  And if you&#8217;re anything like me, perhaps your first question was &#8220;Cool, so what good are they?&#8221;  And I would say &#8220;Excellent question!&#8221; to such an inquiry, because C++ has been doing variadic style templates and functions for a while now.  Even C could do variadic functions with its ellipsis operator and vararg API.  Combine that with function overloading and default function arguments and you&#8217;ve got yourself a pretty powerful variadic function system.</p>
<p>The same goes for C++&#8217;s templates.  Have you ever wondered how <a href="http://www.boost.org/doc/libs/1_37_0/libs/tuple/doc/tuple_users_guide.html">Boost&#8217;s Tuple library</a> works?  Well, Boost does a lot of cool complex things, like defining variadic templates using preprocessor and template metaprogramming, but in the end it&#8217;s actually pretty simple:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">struct</span> NullArg <span style="color: #008000;">&#123;</span><span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
<span style="color: #0000ff;">template</span><span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> Type1 <span style="color: #000080;">=</span> NullArg, <span style="color: #0000ff;">typename</span> Type2 <span style="color: #000080;">=</span> NullArg, <span style="color: #0000ff;">typename</span> Type3 <span style="color: #000080;">=</span> NullArg<span style="color: #000080;">&gt;</span> 
<span style="color: #0000ff;">class</span> tuple <span style="color: #008000;">&#123;</span>
        tuple<span style="color: #008000;">&#40;</span>T0 t0<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span><span style="color: #008000;">&#125;</span>
        tuple<span style="color: #008000;">&#40;</span>T0 t0, T1 t1<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span><span style="color: #008000;">&#125;</span>
        tuple<span style="color: #008000;">&#40;</span>T0 t0, T1 t1, T2 t2<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> t<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></div></div>

<p>Of course this tuple class doesn&#8217;t store or let you retrieve arguments, only allows for up to three parameters (adding more arguments, while monotonous without some preprocessor fun, is easy), and there&#8217;s some definite metaprogramming magics that go into tuple&#8217;s get&lt;X&gt;() template function, but it&#8217;s all still possible.</p>
<p>Getting back to the point: alright so we can, in effect, do variadic templates already, even without fancy C++0x.  So why are they good?  Well, all we&#8217;re really able to do is emulate variadic templates.  The compiler always sees those &#8220;variadic&#8221; structs as having the maximum number of parameters, which means extremely long mangled names (increased binary size), slower compilation time, stupidly complex compiler diagnostic output, and did I mention slower compilation time?  Not to mention that it&#8217;s an ugly and hacky way to achieve something that could be much more elegant.  It&#8217;s fine for libraries to define handy structs with variadic emulation, but do you really want your production code nastied up like that?  Likely not. </p>
<p>So, in come&#8217;s C++0x&#8217;s variadic templates.  They&#8217;re easy, fun, and the whole family can use them!  The syntax looks like this:</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>... <span style="color: #007788;">Args</span><span style="color: #000080;">&gt;</span> 
<span style="color: #0000ff;">class</span> tuple <span style="color: #008000;">&#123;</span><span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
&nbsp;
tuple<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">char</span>, <span style="color: #0000ff;">int</span>, <span style="color: #0000ff;">bool</span><span style="color: #000080;">&gt;</span> t<span style="color: #008080;">;</span></pre></div></div>

<p>Not so useful yet, but as you can see the ellipsis operator is given new purpose, and in this case it&#8217;s meant to denote a template parameter pack.  It can also be used to denote a parameter pack expansion, like this:</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>... <span style="color: #007788;">Args</span><span style="color: #000080;">&gt;</span> 
<span style="color: #0000ff;">class</span> tuple <span style="color: #008000;">&#123;</span>
        tuple<span style="color: #008000;">&#40;</span>Args...<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span><span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
&nbsp;
tuple<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">char</span>, <span style="color: #0000ff;">int</span>, <span style="color: #0000ff;">bool</span><span style="color: #000080;">&gt;</span> t<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">'1'</span>, <span style="color: #0000dd;">2</span>, <span style="color: #0000ff;">false</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></pre></div></div>

<p>Here we&#8217;ve created a variadic tuple template and expanded the Args parameter pack in the constructor, thus letting us pass a variable number of arguments to the tuple&#8217;s constructor.</p>
<p>You can use the pack expansion pretty much anywhere it makes sense: base classes, constructor initializers, you name it, but in my opinion the real power of variadics comes once you start using them in conjunction with template functions and we begin to utilize C++&#8217;s powers of argument deduction.  Take a look at this:</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>... <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>Args...<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span><span style="color: #008000;">&#125;</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;</span><span style="color: #0000ff;">typename</span>... <span style="color: #007788;">Args</span><span style="color: #000080;">&gt;</span>
tuple<span style="color: #000080;">&lt;</span>Args...<span style="color: #000080;">&gt;</span> make_tuple<span style="color: #008000;">&#40;</span>Args... <span style="color: #007788;">args</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        <span style="color: #0000ff;">return</span> tuple<span style="color: #000080;">&lt;</span>Args...<span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span>args...<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">int</span> main<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        <span style="color: #0000ff;">auto</span> t1 <span style="color: #000080;">=</span> make_tuple<span style="color: #008000;">&#40;</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: #008000;">&#41;</span><span style="color: #008080;">;</span>
        <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Nice and clean!  There&#8217;s no need to specify all the template arguments to make_tuple because the compiler deduces them from the function arguments!  Also note the use of the C++0x auto keyword there.  Auto variables are still statically typed, they just get their type set to whatever initializes them.</p>
<p>So there&#8217;s the ultra-basics.  Up next I&#8217;m going to start exploring what you can really do with variadic templates &#8212; like how you can extract an arbitrary element from a pack, pack searching, and other fun compile time trickery.  You&#8217;d think Bjarne might have wanted to allow random access to variadic parameter lists, but that just wouldn&#8217;t be any fun.  Why do things with random access when you can do it all with recursion!</p>
<p>Ready for more?  Head to <a href="/blog/2009-02-18/fun-with-variadic-templates-part-i/">Part II</a>!</p>
]]></content:encoded>
			<wfw:commentRss>http://timburrell.net/blog/2009-02-18/fun-with-variadic-templates-part-i/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>QAwesomeness: Reflection in C++ with Qt</title>
		<link>http://timburrell.net/blog/2009-01-21/qawesomeness-reflection-in-c-with-qt/</link>
		<comments>http://timburrell.net/blog/2009-01-21/qawesomeness-reflection-in-c-with-qt/#comments</comments>
		<pubDate>Wed, 21 Jan 2009 12:27:27 +0000</pubDate>
		<dc:creator>Tim.</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Qt]]></category>
		<category><![CDATA[Review]]></category>

		<guid isPermaLink="false">http://timburrell.net/?p=398</guid>
		<description><![CDATA[<p>In case you&#8217;ve been living under a rock or something and haven&#8217;t heard about Qt, it&#8217;s a cross-platform application framework that&#8217;s most famously known for being the underlying widget toolkit for the KDE desktop environment for *nixes.<br />
Prior to a couple weeks ago I had never played with Qt, and I actually had sort of a [...]</p>

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

	<a rel="nofollow" target="_blank" href="mailto:?subject=QAwesomeness%3A%20Reflection%20in%20C%2B%2B%20with%20Qt&amp;body=http%3A%2F%2Ftimburrell.net%2Fblog%2F2009-01-21%2Fqawesomeness-reflection-in-c-with-qt%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-01-21%2Fqawesomeness-reflection-in-c-with-qt%2F&amp;title=QAwesomeness%3A%20Reflection%20in%20C%2B%2B%20with%20Qt" 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-01-21%2Fqawesomeness-reflection-in-c-with-qt%2F&amp;title=QAwesomeness%3A%20Reflection%20in%20C%2B%2B%20with%20Qt" 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-01-21%2Fqawesomeness-reflection-in-c-with-qt%2F&amp;title=QAwesomeness%3A%20Reflection%20in%20C%2B%2B%20with%20Qt" 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-01-21%2Fqawesomeness-reflection-in-c-with-qt%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=QAwesomeness%3A%20Reflection%20in%20C%2B%2B%20with%20Qt&amp;url=http%3A%2F%2Ftimburrell.net%2Fblog%2F2009-01-21%2Fqawesomeness-reflection-in-c-with-qt%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-01-21%2Fqawesomeness-reflection-in-c-with-qt%2F&amp;title=QAwesomeness%3A%20Reflection%20in%20C%2B%2B%20with%20Qt" 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-01-21%2Fqawesomeness-reflection-in-c-with-qt%2F&amp;t=QAwesomeness%3A%20Reflection%20in%20C%2B%2B%20with%20Qt" 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-01-21%2Fqawesomeness-reflection-in-c-with-qt%2F&amp;title=QAwesomeness%3A%20Reflection%20in%20C%2B%2B%20with%20Qt&amp;source=timburrell.net+All+that+is+Tim+Burrell&amp;summary=In%20case%20you%27ve%20been%20living%20under%20a%20rock%20or%20something%20and%20haven%27t%20heard%20about%20Qt%2C%20it%27s%20a%20cross-platform%20application%20framework%20that%27s%20most%20famously%20known%20for%20being%20the%20underlying%20widget%20toolkit%20for%20the%20KDE%20desktop%20environment%20for%20%2Anixes.%0D%0A%0D%0APrior%20to%20a%20" 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-01-21%2Fqawesomeness-reflection-in-c-with-qt%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-01-21%2Fqawesomeness-reflection-in-c-with-qt%2F&amp;title=QAwesomeness%3A%20Reflection%20in%20C%2B%2B%20with%20Qt" 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-01-21/qawesomeness-reflection-in-c-with-qt/#comments">Comments (3)</a><br />&copy;2010 <a href="http://timburrell.net">timburrell.net</a>. All Rights Reserved.</em></small>]]></description>
			<content:encoded><![CDATA[<p>In case you&#8217;ve been living under a rock or something and haven&#8217;t heard about <a href="http://en.wikipedia.org/wiki/Qt_(toolkit)">Qt</a>, it&#8217;s a cross-platform application framework that&#8217;s most famously known for being the underlying widget toolkit for the <a href="http://kde.org">KDE</a> desktop environment for *nixes.</p>
<p>Prior to a couple weeks ago I had never played with Qt, and I actually had sort of a negative opinion of it.  I had known that it required this extra compilation step where it preprocessed C++ source files for some reason&#8230; but I&#8217;ll back get to that soon &#8212; for now I&#8217;ll just say I thought it was silly because I didn&#8217;t understand it.  The other thing I thought was that Qt was just a widget toolkit for building GUI applications.</p>
<p>I was wrong.  On both accounts.  First of all Qt is so much more than just a GUI API.  It&#8217;s an amazingly well designed collection of classes for building robust cross-platform apps.  Example, the <a href="http://doc.trolltech.com/qstring.html">QString</a> class is so much more useful than std::string.  It has built in support for all types of unicode strings, and has a ton of handy functions and operators available.  Memory management is also really well done in Qt &#8212; you can often &#8220;new and forget&#8221;.  It has a high performance computing API that includes out of the box support for things like <a href="http://en.wikipedia.org/wiki/Map_Reduce">Map-Reduce</a>, job scheduling, futures, etc.  I could go on and on, but suffice to say, Qt is another tool I&#8217;m really glad to put into my toolbox right next to <a href="http://boost.org">Boost</a>.</p>
<p>As a quick aside, before getting to my actual point, I&#8217;d like to mention <a href="http://en.wikipedia.org/wiki/Nokia">Nokia</a>&#8217;s recent acquisition of <a href="http://en.wikipedia.org/wiki/Trolltech">Trolltech</a> (the company responsible for Qt), and their decision to <a href="http://en.wikipedia.org/wiki/GNU_Lesser_General_Public_License">LGPL</a> the library.  I think that this is probably the greatest thing that has happened to Linux, since the Linux kernel itself, and perhaps the GNU tool collection.  I honestly can&#8217;t see why any developer would continue to support and use <a href="http://www.gnome.org/">Gnome</a> now that Qt is LGPL&#8217;ed, and you can use it to write cross-platform apps that use native widgets on Mac, Windows, and Linux.  Competition is usually good, but not when it comes to competing desktop widget sets.</p>
<p>Alright, my actual point, and the thing that inspired me to post about Qt in the first place: the MOC.  Qt&#8217;s Meta Object compiler.  What it does is preprocess a C++ header and build another header out of it that you then include into your source file along side the original header.  This preprocessing step gleans all of the information from your class(es) and puts it into a format digestible at runtime.  Qt has kindly wrapped this up into a nice <a href="http://doc.trolltech.com/metaobjects.html">meta object system</a> that stems from the <a href="http://doc.trolltech.com/qmetaobject.html">QMetaObject</a>.</p>
<p>Essentially what they&#8217;ve done is given <a href="http://en.wikipedia.org/wiki/Reflection_(computer_science)">reflection</a> to C++.  If you&#8217;ve ever programmed in languages like Python, Ruby, Objective-C, C#, or Java, and friends, you know how awesome and useful reflection is.  With Qt&#8217;s MOC system you can do many of the neat things in C++ that you can in dynamically bound languages.  You can enumerate all the methods of a class, and then invoke them via a string representation of their function name.  You can dynamically cast to and from super-classes (again, via a string), or iterate over an object&#8217;s class hierarchy &#8212; all at runtime!  It&#8217;s awesome.  Really awesome.</p>
<p>But, does this extra MOC step require some insane build system?  Well, fortunately no!  Thanks to the KDE project having adopted <a href="http://cmake.org">CMake</a> as their build system they&#8217;ve created all the necessary build scripts for using Qt in your project.  You just do your build setup like you normally would with CMake, include the Qt CMake module, which automatically detects the Qt libraries, and sets up support for automoc&#8217;ing your source files.</p>
<p>And while I&#8217;m on the topic I might as well say a few words about Qt as a GUI library.  I&#8217;ve use quite a few GUI APIs in my day: everything from raw WIN32, to MFC, and .net&#8217;s WPF (Windows Forms), Cocoa and Carbon, WxWidgets, GTK, TK, AWT, Swing, and there&#8217;s probably a few others in there that I&#8217;ve [likely thankfully] forgotten [or repressed].</p>
<p>In the past, I&#8217;ve never really been impressed by a GUI API before.  Cocoa is the one I&#8217;ve used the least, but I was definitely impressed by it &#8212; that being said it&#8217;s sort of wrapped up in the Objective-C way of doing things, which isn&#8217;t necessarily bad, but it&#8217;s a bit more difficult to evaluate on its own because of that fact.  Windows Forms is also relatively well done, but nothing to write home about.  And the rest are just plain awful.  With the shining star being Qt.  </p>
<p>When I created my first Qt GUI (through the help of <a href="http://www.qtsoftware.com/products/appdev/developer-tools/developer-tools">Qt&#8217;s excellent GUI designer</a>) I was extremely happy.  I&#8217;ll be the first to admit that I hate GUI programming, but let&#8217;s face it, every once in a while you do need an app with a GUI, and Qt takes all the crap work out of GUI programming.  There&#8217;s almost never a need to write code that resizes widgets when you resize your application&#8217;s window (they have a well thought out <a href="http://doc.trolltech.com/layout.html">Layout system</a>), and the whole process of designing a GUI and including it in your app is very well done.</p>
<p>The GUI designer creates a nice human readable XML file that you can either have your CMake build system auto-process for you and produce C++ code that you merely include into your project, or you can use the Qt library to dynamically load and process the UI XML files at runtime.  Who doesn&#8217;t want their users to be able to change your GUI around in whatever twisted ways they want?  Well okay, probably a lot of people, but at least the option is there!</p>
<p>All in all I give Qt a resounding thumbs up.  I will probably use it in every spare-time project I do from now on, even non-graphical ones, just because I think the API is that good &#8212; Qt really has given C++ a gift with their meta-object system.  And now with Nokia&#8217;s support and LGPL goodness, there&#8217;s finally no reason not to use Qt.</p>
]]></content:encoded>
			<wfw:commentRss>http://timburrell.net/blog/2009-01-21/qawesomeness-reflection-in-c-with-qt/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Effective C++: Cyclical Dependencies</title>
		<link>http://timburrell.net/blog/2008-11-23/effective-c-cyclical-dependencies/</link>
		<comments>http://timburrell.net/blog/2008-11-23/effective-c-cyclical-dependencies/#comments</comments>
		<pubDate>Sun, 23 Nov 2008 19:08:09 +0000</pubDate>
		<dc:creator>Tim.</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Effective C++]]></category>
		<category><![CDATA[HowTo]]></category>
		<category><![CDATA[Programming languages]]></category>

		<guid isPermaLink="false">http://timburrell.net/?p=369</guid>
		<description><![CDATA[<p>I&#8217;ve noticed over the years that for the majority of computer scientists design is something we either love or hate.  And however unfortunate it may be, I think either way design is usually a bit of an after thought, or at the least it&#8217;s a moving target.  High level design can usually be [...]</p>

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

	<a rel="nofollow" target="_blank" href="mailto:?subject=Effective%20C%2B%2B%3A%20Cyclical%20Dependencies&amp;body=http%3A%2F%2Ftimburrell.net%2Fblog%2F2008-11-23%2Feffective-c-cyclical-dependencies%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%2F2008-11-23%2Feffective-c-cyclical-dependencies%2F&amp;title=Effective%20C%2B%2B%3A%20Cyclical%20Dependencies" 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%2F2008-11-23%2Feffective-c-cyclical-dependencies%2F&amp;title=Effective%20C%2B%2B%3A%20Cyclical%20Dependencies" 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%2F2008-11-23%2Feffective-c-cyclical-dependencies%2F&amp;title=Effective%20C%2B%2B%3A%20Cyclical%20Dependencies" 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%2F2008-11-23%2Feffective-c-cyclical-dependencies%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=Effective%20C%2B%2B%3A%20Cyclical%20Dependencies&amp;url=http%3A%2F%2Ftimburrell.net%2Fblog%2F2008-11-23%2Feffective-c-cyclical-dependencies%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%2F2008-11-23%2Feffective-c-cyclical-dependencies%2F&amp;title=Effective%20C%2B%2B%3A%20Cyclical%20Dependencies" 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%2F2008-11-23%2Feffective-c-cyclical-dependencies%2F&amp;t=Effective%20C%2B%2B%3A%20Cyclical%20Dependencies" 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%2F2008-11-23%2Feffective-c-cyclical-dependencies%2F&amp;title=Effective%20C%2B%2B%3A%20Cyclical%20Dependencies&amp;source=timburrell.net+All+that+is+Tim+Burrell&amp;summary=I%27ve%20noticed%20over%20the%20years%20that%20for%20the%20majority%20of%20computer%20scientists%20design%20is%20something%20we%20either%20love%20or%20hate.%20%20And%20however%20unfortunate%20it%20may%20be%2C%20I%20think%20either%20way%20design%20is%20usually%20a%20bit%20of%20an%20after%20thought%2C%20or%20at%20the%20least%20it%27s%20a%20moving%20tar" 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%2F2008-11-23%2Feffective-c-cyclical-dependencies%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%2F2008-11-23%2Feffective-c-cyclical-dependencies%2F&amp;title=Effective%20C%2B%2B%3A%20Cyclical%20Dependencies" 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/2008-11-23/effective-c-cyclical-dependencies/#comments">Leave a Comment</a><br />&copy;2010 <a href="http://timburrell.net">timburrell.net</a>. All Rights Reserved.</em></small>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve noticed over the years that for the majority of computer scientists design is something we either love or hate.  And however unfortunate it may be, I think either way design is usually a bit of an after thought, or at the least it&#8217;s a moving target.  High level design can usually be done in advance, but for large projects the design almost always needs to be tweaked on the fly as new issues crop up.</p>
<p>I, personally, am in the camp that loves design.  I have seen some beautifully elegant code written by crazy geniuses <i>&lt;cough&gt;John Carmack&lt;/cough&gt;</i> that was&#8230; <a href="ftp://ftp.idsoftware.com/idstuff/source/quake3-1.32b-source.zip">less than well designed</a>, but most of the programs I admire (of which I also have access to the source code) generally have equally <a href="http://www.ogre3d.org/index.php?option=com_content&#038;task=view&#038;id=412&#038;Itemid=132">admirable design philosophies</a>.</p>
<p>But, this isn&#8217;t a perfect world.  It&#8217;s a bit sad that we still haven&#8217;t figured out a way to hook computers directly to our brains, so we&#8217;re left with using terribly inefficient and somewhat cumbersome programming languages to wrangle these computation machines into doing something close to what we wish them to.  Of course they have the irritating habit of doing exactly what we tell them, rather than what we mean.</p>
<p>I bring this point up because although programmer skill is definitely one issue, languages themselves suffer from design issues, and I&#8217;d say a good majority of the time that&#8217;s spent struggling with design is actually spent struggling with a language&#8217;s design.  It&#8217;s the same battle artists have fought for years:  I&#8217;ve got a beautiful image in my head, now how do I get this paint brush to paint that image on this canvas?</p>
<p>For this series of of articles I&#8217;m going to pick on C++.  Love it or hate it&#8217;s so prevalent that even if you&#8217;re one who spends most of your time with more modern languages like Ruby, Python, and Haskell, you&#8217;re still likely forced to bust out some C++ now and again.  And for those of us who spend 40 hours a week (or more) with C++ and love it, I&#8217;m sure we&#8217;ve all got a fairly lengthy laundry list of problems that don&#8217;t necessary come out as clean as we&#8217;d like when we put them into the crazy kitchen sink that is C++.  So basically, I&#8217;m going to pick on C++ because it&#8217;s easy &#8212; that and the fact that I&#8217;m a C++ compiler developer by day, so I may have a somewhat unique perspective on the language.</p>
<p>For this first Effective C++ installment I&#8217;m going to start off slow.  I&#8217;ve got plans to dive into some more advanced things like template metaprogramming and some of the upcoming C++0x features down the road, but I thought first I&#8217;d tackle a problem that&#8217;s plagued me more than once, and in more languages than just C++ over the years.  It&#8217;s also an issue that I&#8217;ve seen some fairly&#8230; wacky (I&#8217;m being nice)&#8230; solutions to by students and even in some open source code in the past: it&#8217;s the joyous design problem known as the cyclomatic dependency.</p>
<p>But before I begin let me just say: there&#8217;s no judging here.  Say what you want, but I know as well as the next, given certain circumstances sometimes a goto, or a <a href="http://en.wikipedia.org/wiki/Duff%27s_device">Duff&#8217;s device</a> can actually be an elegant solution, so I&#8217;m not going to sit here and say &#8220;rethink your design&#8221;, I&#8217;m going to trust that you have, and move on.  Fact is, you&#8217;ve run into an issue where you need to have class A depend on class B, and class B on A.  Let&#8217;s look at an example:</p>
<p>Here is NetworkServer.hpp:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #339900;">#include &quot;NetworkConnection.hpp&quot;</span>
&nbsp;
<span style="color: #0000ff;">class</span> NetworkServer <span style="color: #008000;">&#123;</span>
        list<span style="color: #000080;">&lt;</span>NetworkConnection<span style="color: #000080;">&gt;</span> mConnections<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></pre></div></div>

<p>And here&#8217;s NetworkConnection.hpp:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #339900;">#include &quot;NetworkServer.hpp&quot;</span>
&nbsp;
<span style="color: #0000ff;">class</span> NetworkConnection <span style="color: #008000;">&#123;</span>
<span style="color: #0000ff;">public</span><span style="color: #008080;">:</span>
	NetworkConnection<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> NetworkServer<span style="color: #000040;">&amp;</span> server<span style="color: #008000;">&#41;</span> <span style="color: #008080;">:</span> mServer<span style="color: #008000;">&#40;</span>server<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #0000ff;">private</span><span style="color: #008080;">:</span>
	NetworkServer<span style="color: #000040;">&amp;</span> mServer<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></pre></div></div>

<p>You can immediately spot the issue.  Now, of course, this simplistic problem could be reworked in any number of ways to avoid the cyclical dependency, but real world problems are often much more complex and thus harder to refactor, yet often come down to some variation of the above.</p>
<p>Fortunately C++ actually has a fairly decent solution to this problem: the forward declaration.  It&#8217;s simple, and it works well, but before looking at it, let me say that I&#8217;ve seen enough work arounds to know there&#8217;s plenty of C++ programmers out there who don&#8217;t know what a forward declaration is, or if they do, why it&#8217;s useful, or what the C++ compiler actually does with it.</p>
<p>One of the solutions I&#8217;ve seen to this is to use generic programming, or in C++ speak: templates.  We could define NetworkConnection like so:</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> T<span style="color: #000080;">&gt;</span>
<span style="color: #0000ff;">class</span> NetworkConnection <span style="color: #008000;">&#123;</span>
<span style="color: #0000ff;">public</span><span style="color: #008080;">:</span>
	NetworkConnection<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> T<span style="color: #000040;">&amp;</span> server<span style="color: #008000;">&#41;</span> <span style="color: #008080;">:</span> mServer<span style="color: #008000;">&#40;</span>server<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #0000ff;">private</span><span style="color: #008080;">:</span>
	T<span style="color: #000040;">&amp;</span> mServer<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></pre></div></div>

<p>This works, but what if someone instantiates NetworkConnection with a type that doesn&#8217;t provide the same methods as NetworkServer &#8212; broken design!  Not only that but if you&#8217;re using NetworkConnection as a base class it might not make sense to have it templated because you might need to cast from it to a super class, and you might not know what it was instantiated with at casting time.  This is actually a design flaw with C++, and is being addressed with the upcoming C++0x language feature known as concepts (which I intend to look at in detail in a future installment).</p>
<p>There&#8217;s also a non-template way to deal with this issue, however, and it&#8217;s something I&#8217;ve seen used a lot, especially by students (who are, through no fault of their own, ingrained in the java-single-inheritance-heavy-on-the-interface style of design).  You simply make class A inherit from an abstract base class that provides pure virtual function interfaces to the methods needed by the other class caught in the cyclical loop.  Then pass the abstract class around rather than its implementation and voila, dependency avoided:</p>
<p>NetworkServerInterface.hpp:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">struct</span> NetworkServerInterface <span style="color: #008000;">&#123;</span>
	<span style="color: #0000ff;">virtual</span> <span style="color: #0000ff;">void</span> someFuncA<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>
	<span style="color: #0000ff;">virtual</span> <span style="color: #0000ff;">bool</span> someFuncB<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <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>NetworkServer.hpp:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #339900;">#include &quot;NetworkServerInterface.hpp&quot;</span>
<span style="color: #339900;">#include &quot;NetworkConnection.hpp&quot;</span>
&nbsp;
<span style="color: #0000ff;">class</span> NetworkServer <span style="color: #008080;">:</span> <span style="color: #0000ff;">public</span> NetworkServerInterface <span style="color: #008000;">&#123;</span>
<span style="color: #0000ff;">public</span><span style="color: #008080;">:</span>
	<span style="color: #0000ff;">void</span> someFuncA<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
	<span style="color: #0000ff;">bool</span> SomeFuncB<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #0000ff;">private</span><span style="color: #008080;">:</span>
	list<span style="color: #000080;">&lt;</span>NetworkConnection<span style="color: #000080;">&gt;</span> mConnections<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></pre></div></div>

<p>NetworkConnection.hpp:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #339900;">#include &quot;NetworkServerInterface.hpp&quot;</span>
&nbsp;
<span style="color: #0000ff;">class</span> NetworkConnection <span style="color: #008000;">&#123;</span>
<span style="color: #0000ff;">public</span><span style="color: #008080;">:</span>
	NetworkConnection<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> NetworkServerInterface<span style="color: #000040;">&amp;</span> server<span style="color: #008000;">&#41;</span> <span style="color: #008080;">:</span> mServer<span style="color: #008000;">&#40;</span>server<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> mServer.<span style="color: #007788;">someFuncA</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: #0000ff;">private</span><span style="color: #008080;">:</span>
	NetworkServerInterface<span style="color: #000040;">&amp;</span> mServer<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></pre></div></div>

<p>This works, and can be a good technique to enforece certain design principles (it&#8217;s easy to only allow specific objects to use the NetworkServer in exactly the way you want by only providing a subset of functions in the abstract class definition), but it&#8217;s not without its shortcomings.  Firstly, significant development effort is wasted by requiring the interface class and main class be kept in sync.  Then there&#8217;s the overhead of virtual function calls that should be considered.  For a time critical section of code this scenario should be avoided like the plague. </p>
<p>Another possible solution is the dreaded void *.  It&#8217;s a holdover from the days of C programming, and much like the goto, is generally frowned upon in modern OO design.  The problem with using a void pointer is if you need to use the member variable as its actual type then you have to cast it back and you&#8217;re left with the same cyclical dependency because then you need to include the casted type&#8217;s header file again.</p>
<p>Fortunately with C++, since the headers no longer include one another, and the translation unit is often broken into separate header and source files, you&#8217;re free to include any headers you wish in the parts of the translation unit that contain the implementation definitions (the cpp files).  So, you could store the variable as a void pointer and cast from it whenever you need to access its actual type&#8217;s methods, ie:</p>
<p>NetworkConnection.hpp</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">class</span> NetworkConnection <span style="color: #008000;">&#123;</span>
<span style="color: #0000ff;">public</span><span style="color: #008080;">:</span>
	NetworkConnection<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #000040;">*</span> server<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #0000ff;">private</span><span style="color: #008080;">:</span>
	<span style="color: #0000ff;">void</span><span style="color: #000040;">*</span> mpServer<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></pre></div></div>

<p>NetworkConnection.cpp:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #339900;">#include &quot;NetworkConnection.hpp&quot;</span>
<span style="color: #339900;">#include &quot;NetworkServer.hpp&quot;</span>
&nbsp;
NetworkConnection<span style="color: #008080;">::</span><span style="color: #007788;">NetworkConnection</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #000040;">*</span> server<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
	mpServer <span style="color: #000080;">=</span> server<span style="color: #008080;">;</span>
	<span style="color: #0000ff;">static_cast</span><span style="color: #000080;">&lt;</span>NetworkServer<span style="color: #000040;">*</span><span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span>server<span style="color: #008000;">&#41;</span><span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>someFuncA<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Yep, this works, but it&#8217;s nasty ugly, and kills proper design because you can&#8217;t really return the void pointer from public facing functions in any safe way.  Normally I wouldn&#8217;t even bring this up, but it is an option, and it&#8217;s also a precursor to the forward declaration.</p>
<p>Essentially with forward declarations you&#8217;re telling the compiler that you want to use a class without knowing anything about it.  In compiler terminology basically you&#8217;re doing namelookup, and that&#8217;s about it.  You can&#8217;t use any objects of that type until you give the compiler the details it needs.  This is fine though, because you can make sure to only use the variable after its class definition is available (ie in out of line member functions, or in the implementation part of the translation unit).  Here&#8217;s an example:</p>
<p>NetworkServer.hpp:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #339900;">#include &quot;NetworkConnection.hpp&quot;</span>
&nbsp;
<span style="color: #0000ff;">class</span> NetworkServer <span style="color: #008000;">&#123;</span>
<span style="color: #0000ff;">public</span><span style="color: #008080;">:</span>
	<span style="color: #0000ff;">int</span> someFuncA<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span>
<span style="color: #0000ff;">private</span><span style="color: #008080;">:</span>
	list<span style="color: #000080;">&lt;</span>NetworkConnection<span style="color: #000080;">&gt;</span> mConnections<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></pre></div></div>

<p>NetworkConnection.hpp:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">class</span> NetworkServer<span style="color: #008080;">;</span> <span style="color: #666666;">// Foward declaration</span>
&nbsp;
<span style="color: #0000ff;">class</span> NetworkConnection <span style="color: #008000;">&#123;</span>
<span style="color: #0000ff;">public</span><span style="color: #008080;">:</span>
	NetworkConnection<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> NetworkServer<span style="color: #000040;">&amp;</span> server<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #0000ff;">private</span><span style="color: #008080;">:</span>
	NetworkServer<span style="color: #000040;">&amp;</span> mServer<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></pre></div></div>

<p>NetworkConnection.cpp:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #339900;">#include &quot;NetworkConnection.hpp&quot;</span>
<span style="color: #339900;">#include &quot;NetworkServer.hpp&quot;</span>
&nbsp;
NetworkConnection<span style="color: #008080;">::</span><span style="color: #007788;">NetworkConnection</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> NetworkServer<span style="color: #000040;">&amp;</span> server<span style="color: #008000;">&#41;</span> <span style="color: #008080;">:</span> mServer<span style="color: #008000;">&#40;</span>server<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
	mServer.<span style="color: #007788;">someFuncA</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Not only does this solve the cyclical dependency issue, but it speeds up compilation times as well.  I&#8217;d even go as far as to say it&#8217;s good practice to use forward declarations wherever possible, which is in most header files if you&#8217;re writing a traditional application or a library that&#8217;s not meant to be completely header based.</p>
<p>So there you have it, a look at how to deal with cyclical dependencies in C++.</p>
<p>I&#8217;m thinking that the next topic will be a multi-part series on the upcoming <a href="http://www.generic-programming.org/~dgregor/cpp/brief-intro.pdf">variadic</a> <a href="www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2152.pdf">templates</a> feature of C++0x since you can already play with them via gcc >= 4.3.  Plus my goal is to eventually focus on more metaprogramming type stuff, and variadics are going to make that a lot more fun.</p>
]]></content:encoded>
			<wfw:commentRss>http://timburrell.net/blog/2008-11-23/effective-c-cyclical-dependencies/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>D Postmortem</title>
		<link>http://timburrell.net/blog/2008-06-22/d-postmortem/</link>
		<comments>http://timburrell.net/blog/2008-06-22/d-postmortem/#comments</comments>
		<pubDate>Sun, 22 Jun 2008 12:43:17 +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[D]]></category>
		<category><![CDATA[Parallel programming]]></category>
		<category><![CDATA[Programming languages]]></category>
		<category><![CDATA[Review]]></category>

		<guid isPermaLink="false">http://timburrell.net/?p=358</guid>
		<description><![CDATA[<p>It&#8217;s been about a year and half since I started actively using D &#8212; I&#8217;ve written (and maintained) a couple of small commercial applications in it, and taken maintainership over a couple of D related open source projects, but most of my experience with the language comes from using it to write my thesis project [...]</p>

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

	<a rel="nofollow" target="_blank" href="mailto:?subject=D%20Postmortem&amp;body=http%3A%2F%2Ftimburrell.net%2Fblog%2F2008-06-22%2Fd-postmortem%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%2F2008-06-22%2Fd-postmortem%2F&amp;title=D%20Postmortem" 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%2F2008-06-22%2Fd-postmortem%2F&amp;title=D%20Postmortem" 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%2F2008-06-22%2Fd-postmortem%2F&amp;title=D%20Postmortem" 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%2F2008-06-22%2Fd-postmortem%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=D%20Postmortem&amp;url=http%3A%2F%2Ftimburrell.net%2Fblog%2F2008-06-22%2Fd-postmortem%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%2F2008-06-22%2Fd-postmortem%2F&amp;title=D%20Postmortem" 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%2F2008-06-22%2Fd-postmortem%2F&amp;t=D%20Postmortem" 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%2F2008-06-22%2Fd-postmortem%2F&amp;title=D%20Postmortem&amp;source=timburrell.net+All+that+is+Tim+Burrell&amp;summary=It%27s%20been%20about%20a%20year%20and%20half%20since%20I%20started%20actively%20using%20D%20--%20I%27ve%20written%20%28and%20maintained%29%20a%20couple%20of%20small%20commercial%20applications%20in%20it%2C%20and%20taken%20maintainership%20over%20a%20couple%20of%20D%20related%20open%20source%20projects%2C%20but%20most%20of%20my%20experience%20wit" 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%2F2008-06-22%2Fd-postmortem%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%2F2008-06-22%2Fd-postmortem%2F&amp;title=D%20Postmortem" 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/2008-06-22/d-postmortem/#comments">Comments (8)</a><br />&copy;2010 <a href="http://timburrell.net">timburrell.net</a>. All Rights Reserved.</em></small>]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s been about a year and half since I started actively using <a href="http://digitalmars.com/d">D</a> &#8212; I&#8217;ve written (and maintained) a couple of small commercial applications in it, and taken maintainership over a couple of D related open source projects, but most of my experience with the language comes from using it to write my thesis project in &#8212; around 30,000 lines of code spread over 100 source files.  Not exactly a huge project, but large enough to get a good feel for the language.</p>
<p>First of all the good: the bottom line is, D is a great little language, and I say little because in many ways it&#8217;s a lot simpler, and less complicated than any of the other system level object-oriented languages that it competes with (C++).  This doesn&#8217;t mean that D is any less valuable though &#8212; in fact much the opposite.  D&#8217;s inherent simplicity is by design.  It&#8217;s pretty clear by looking at the <a href="http://digitalmars.com/d/1.0/lex.html">language spec</a> that the idea was to take the best elements of some languages, throw out the rest, and add some of the missing features that we all wish we had (built in strings, optional garbage collection, modern language features, etc).</p>
<p>And by modern language features, this is the kind of stuff I&#8217;m talking about: <a href="http://www.digitalmars.com/d/1.0/mixin.html">mixins</a>, <a href="http://www.digitalmars.com/d/1.0/expression.html#FunctionLiteral">lambdas</a>, <a href="http://www.digitalmars.com/d/1.0/variadic-function-templates.html">variadic templates</a>, <a href="http://www.digitalmars.com/d/1.0/lazy-evaluation.html">lazy evaluation</a>, <a href="http://www.digitalmars.com/d/1.0/function.html#closures">delegates</a>, <a href="http://www.digitalmars.com/d/1.0/function.html#nested">nested functions</a>, <a href="http://www.digitalmars.com/d/1.0/struct.html">anonymous unions</a>, <a href="http://www.digitalmars.com/d/1.0/arrays.html#slicing">array slicing</a>, <a href="http://www.digitalmars.com/d/1.0/dbc.html">contract programming</a>, <a href="http://www.digitalmars.com/d/1.0/statement.html#ForeachStatement">handy statements</a>.  Basically, much of C++0x&#8217;s upcoming feature set, and more.</p>
<p>So does D deliver?  The answer yes, a resounding yes in fact.  In terms of core language design and features, D provides exactly what many of us have been yearning for for years &#8212; a system level language that is on par with (or better than) modern scripting languages (such as Python, and Ruby) in terms of development speed, provides the language features we all should have by now, yet compiles to native code that can be as efficient as C++.</p>
<p>The panacea of programming languages?  Well&#8230; no, not quite.  Unfortunately the story doesn&#8217;t end there.</p>
<p>The first problem is a major one, and I don&#8217;t want to downplay it because as it stands it&#8217;s enough of an issue that no development house could even consider D as a prospective language, but fortunately it&#8217;s something that should get better over time.  The issue: compiler bugs, and plenty of them.  Some of them are small, some of them are huge, but there&#8217;s enough that they add up to a serious problem.</p>
<p>The bugs I ran into ranged from little things like floating point printing errors, all the way to compiler segfaults.  Being that D is so young and the compilers aren&#8217;t close to maturity yet, any project complex enough is basically guaranteed to run into problems with either of the existing compilers, and my thesis project was no exception.  Fortunately there are two major compilers that use separate optimization paths (a frequent culprit in the official digitalmars compiler) so one at least has a contingency option, but unfortunately, they share the same front-end, so they tend to exhibit some of the same bugs as well.</p>
<p>There&#8217;s also some serious performance issues with both compilers.   For example, if you look at the assembler output of either of the compilers you can see them doing the same wasteful, redundant memory copies when doing something simple like returning a struct from a function.  The only work around to this compiler bug is to do ugly things like return values from functions using by-reference function parameters.  </p>
<p>Take a moment to think about the case where you can&#8217;t return values from functions &#8212; design goes out the window, along with readability and maintainability, not to mention ease of porting to other languages (should the desire arise).  It extends further than that though &#8212; it means, for example, using custom foreach iterators to do a simple iteration over a collection of stack allocated structs becomes so inefficient that you end up having to put regular for loops in places where they really shouldn&#8217;t be.</p>
<p>Basically these &#8220;little&#8221; compiler issues make it difficult to consistently employ OO design principles, and use all of the nice modern language features that made the language so attractive in the first place.  And after discovering these issues, along with their associated workarounds (wasting time discovering that your program&#8217;s poor performance is due to the compiler and not your code), you&#8217;re basically left with either a slow, inefficient executable, or ugly, unmaintainable code written in a language that was specifically designed to produce clear, concise, elegant code.  </p>
<p>It&#8217;s a terrible shame to have a few minor problems result in such broad consequences, but these issues are all things that can be fixed, and they&#8217;re not nearly as prevalent as this post makes them seem.  In fairness, given how new D is, the overall stability and quality of the available compilers is actually quite impressive.  The language itself shouldn&#8217;t be judged on these compiler issues, but it&#8217;s important that people who may be considering adopting D be aware that there are problems with the compilers before forging ahead.</p>
<p>The next big issue isn&#8217;t technically related to the language itself, but is still a problem because it&#8217;s one of the root causes of much of what&#8217;s stopping D from living up to its potential.  The heart of the matter is that D is currently going through some growing pains, and project leadership isn&#8217;t keeping up with the community.</p>
<p>Right now the D community is split between two incompatible standard libraries (<a href="http://dsource.org/projects/tango">Tango</a>, and <a href="http://www.digitalmars.com/d/1.0/phobos/phobos.html">Phobos</a>) that offer up different design philosophies, and although the majority of the community uses one library (Tango), it&#8217;s not the official standard library.  This tends to create confusion for new users, and forces people to adopt one library or another, or library designers to write and maintain two sets of sources &#8212; neither being optimal solutions.</p>
<p>To come back to the issue of the compiler bugs &#8212; in other projects such a situation might not be as much of an issue, but many of the compiler bugs have been sitting idle in the D bug tracker for many months, and many releases.  It appears as though the project is transitioning between a small niche language, to something that might even be getting close to being considered mainstream (D is currently <a href="http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html">12<sup>th</sup> on the programming language popularity list</a>, and still moving up), so it&#8217;s understandable that some project leadership issues might crop up along the way.</p>
<p>Regardless of how understandable these growing pains may be, it&#8217;s still something that the project maintainers, and the D user community, are going to have to deal with before the language can really take the next step in terms of public acceptance.</p>
<p>There&#8217;s also one final problem with the language, or rather, the upcoming D2 language spec, and as big as all the other issues are this is actually the biggest thing that&#8217;s keeping me from continuing to use D on future projects.  We all know that multi-core systems are the defacto standard these days, and although we&#8217;re starting to get a handle on developing tools to help programmers deal with the almost always non-trivial task of writing parallel code, we&#8217;ve barely even scratched the surface of what compilers and runtimes can do to help regular joe-six-pack-programmer effectively, and easily, design algorithms that take advantage of today&#8217;s processors.</p>
<p>Given the current state of affairs in terms of SMP and distributed development, and that there&#8217;s a new revision of the D language in the works, D has a great opportunity to assert its intent to be a player in the upcoming multiprogramming language war.  But nothing is in the works.  The D team isn&#8217;t actively working on providing any inclusion of a modern parallel programming paradigm for D2, which means it will likely be pushed back to some future release of D.  This is unfortunate, because I know a great many developers are waiting for tools to help them deal with parallel programming (even if they don&#8217;t know they are).</p>
<p>Aside from <a href="http://en.wikipedia.org/wiki/Erlang_(programming_language)">Erlang</a> and other more obscure functional languages, right now C++ is still one of the best choices around for parallel development.  With the resounding success <a href="http://openmp.org">OpenMP</a> has seen in the last few years, and with <a href="http://en.wikipedia.org/wiki/C%2B%2B0x">C++0x</a> on the horizon and the new <a href="http://terboven.spaces.live.com/blog/cns!EA3D3C756483FECB!316.entry">OpenMP 3 being recently released</a> it looks like C++ is going to continue to be the language of choice for most system level and computationally expensive tasks.</p>
<p>Neither D, nor the upcoming D2 spec, give developers anything beyond raw threading (plus some critical section synchronization and resource locking type mechanisms, along with a controversial <a href="http://www.digitalmars.com/d/2.0/const-faq.html">const system</a>), but definitely nothing in the way of a modern parallel programming methodology.  It&#8217;s another unfortunate oversight that takes a language that should be an ultramodern successor to nearly all current languages in its class and puts it years behind C++, and even Fortran (both of which have OpenMP at their disposal), and let&#8217;s not even try to make a comparison to other languages like <a href="http://www.erlang.org/download/getting_started-5.4.pdf">Erlang</a>, <a href="http://jocaml.inria.fr/">JoCaml</a>, <a href="http://www.haskell.org/ghc/docs/6.4/html/users_guide/concurrent-and-parallel.html">Parallel Haskell</a>, and friends.</p>
<p>I really wish I could recommend D as a natural successor to C++, but given all the issues it&#8217;s currently facing, I just can&#8217;t.  It&#8217;s simply not there yet, and I fear, given it&#8217;s current direction, that it never will be.  I still think it&#8217;s a great project, and I hope that it works out because I&#8217;d like very much to see it succeed, because I think a strong competitor to the multi-paradigm system-level language would be a great boon to the software development and computer science communities.</p>
<p>I&#8217;ll definitely keep watching D to see what happens in the future, but I likely won&#8217;t be using it for any more projects until they can iron out the compiler stability and efficiency issues, and implement some reasonable multiprogramming method.</p>
]]></content:encoded>
			<wfw:commentRss>http://timburrell.net/blog/2008-06-22/d-postmortem/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Garbage Collection: The Joy and the Curse</title>
		<link>http://timburrell.net/blog/2008-03-06/garbage-collection-the-joy-and-the-curse/</link>
		<comments>http://timburrell.net/blog/2008-03-06/garbage-collection-the-joy-and-the-curse/#comments</comments>
		<pubDate>Thu, 06 Mar 2008 14:09:15 +0000</pubDate>
		<dc:creator>Tim.</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[D]]></category>
		<category><![CDATA[Garbage collection]]></category>
		<category><![CDATA[Memory management]]></category>

		<guid isPermaLink="false">http://timburrell.net/research/2008-03-06/garbage-collection-the-joy-and-the-curse/</guid>
		<description><![CDATA[<p>Everyone knows the diatribe spouted by certain types of programming evangelists that a good garbage collector can give a program higher memory throughput than one under manual memory management (or some equivalent scheme like reference counting) &#8212; not only that but manually managing your own memory is pretty much a waste of good development time; [...]</p>

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

	<a rel="nofollow" target="_blank" href="mailto:?subject=Garbage%20Collection%3A%20The%20Joy%20and%20the%20Curse&amp;body=http%3A%2F%2Ftimburrell.net%2Fblog%2F2008-03-06%2Fgarbage-collection-the-joy-and-the-curse%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%2F2008-03-06%2Fgarbage-collection-the-joy-and-the-curse%2F&amp;title=Garbage%20Collection%3A%20The%20Joy%20and%20the%20Curse" 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%2F2008-03-06%2Fgarbage-collection-the-joy-and-the-curse%2F&amp;title=Garbage%20Collection%3A%20The%20Joy%20and%20the%20Curse" 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%2F2008-03-06%2Fgarbage-collection-the-joy-and-the-curse%2F&amp;title=Garbage%20Collection%3A%20The%20Joy%20and%20the%20Curse" 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%2F2008-03-06%2Fgarbage-collection-the-joy-and-the-curse%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=Garbage%20Collection%3A%20The%20Joy%20and%20the%20Curse&amp;url=http%3A%2F%2Ftimburrell.net%2Fblog%2F2008-03-06%2Fgarbage-collection-the-joy-and-the-curse%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%2F2008-03-06%2Fgarbage-collection-the-joy-and-the-curse%2F&amp;title=Garbage%20Collection%3A%20The%20Joy%20and%20the%20Curse" 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%2F2008-03-06%2Fgarbage-collection-the-joy-and-the-curse%2F&amp;t=Garbage%20Collection%3A%20The%20Joy%20and%20the%20Curse" 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%2F2008-03-06%2Fgarbage-collection-the-joy-and-the-curse%2F&amp;title=Garbage%20Collection%3A%20The%20Joy%20and%20the%20Curse&amp;source=timburrell.net+All+that+is+Tim+Burrell&amp;summary=Everyone%20knows%20the%20diatribe%20spouted%20by%20certain%20types%20of%20programming%20evangelists%20that%20a%20good%20garbage%20collector%20can%20give%20a%20program%20higher%20memory%20throughput%20than%20one%20under%20manual%20memory%20management%20%28or%20some%20equivalent%20scheme%20like%20reference%20counting%29%20--%20n" 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%2F2008-03-06%2Fgarbage-collection-the-joy-and-the-curse%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%2F2008-03-06%2Fgarbage-collection-the-joy-and-the-curse%2F&amp;title=Garbage%20Collection%3A%20The%20Joy%20and%20the%20Curse" 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/2008-03-06/garbage-collection-the-joy-and-the-curse/#comments">Comments (12)</a><br />&copy;2010 <a href="http://timburrell.net">timburrell.net</a>. All Rights Reserved.</em></small>]]></description>
			<content:encoded><![CDATA[<p>Everyone knows the diatribe spouted by certain types of programming evangelists that a good garbage collector can give a program higher memory throughput than one under manual memory management (or some equivalent scheme like reference counting) &#8212; not only that but manually managing your own memory is pretty much a waste of good development time; no real programmer should have to lower him/herself to dealing with <i>memory</i>.  So the appeal of Garbage Collection is pretty obvious.  Why would anyone want to do their own memory management when you can let the computer do it for you, and at the same time have it work out to be more efficient?</p>
<p>The thing is, garbage collection isn&#8217;t a trivial problem, and it&#8217;s certainly not gotten to the point where it&#8217;s perfect.  Cycles aren&#8217;t really an issue for modern conservative style GC&#8217;s, not like they are with reference counting schemes, but that&#8217;s not to say they don&#8217;t still cause a problem.  Discovering cycles isn&#8217;t free, and generally in a complicated memory setup, even with a good fully modern GC you still end up with weak references / pointers like you would using simple reference counting.</p>
<p>I&#8217;m writing this because I&#8217;ve recently fallen onto the GC bandwagon as I&#8217;ve been using <a href="http://digitalmars.com/d">D</a> quite a bit lately.  Prior to D my only experience with GC was some time spent with Objective-C, and 4 years of undergrad <strike>cursing</strike> using Java &#8212; but that doesn&#8217;t really count <img src='http://timburrell.net/smilies/yahoo_wink.gif' alt='&#59;&#41;' class='wp-smiley' width='18' height='18' title='&#59;&#41;' />, and of course a myriad of interpreted languages like Python, PHP, lua, Ruby, etc.  I have used the <a href="http://www.hpl.hp.com/personal/Hans_Boehm/gc/">Hans Boehm GC</a> with C and C++ a few times as well, but that was for select cases where the scenarios were a good match for a garbage collected system.</p>
<p>After spending some time really working with a GC language (under situations that are less than an ideal use for a GC system &#8212; ie a real-time interactive simulation), I&#8217;ve come up with a more rounded opinion of garbage collection, and I thought I ought to share some of the things I&#8217;ve discovered that the GC pundits don&#8217;t seem to want you to know:</p>
<ul>
<li>Managing memory using GC, in complex data structure situations, where weak ref&#8217;s and cyclical dependencies are required (pretty much every largish program every written), can be more complicated and time consuming than manual memory management.  If someone tells you GC is all about &#8220;<b>new</b> and forget&#8221;, while it is true much of the time, you&#8217;re still okay to give them a good kidney punch because they&#8217;ve never really used GC.</li>
<li>Memory leaks are not impossible with GC.  It doesn&#8217;t take much to fool a GC system into believing memory should be retained when it shouldn&#8217;t.  This is a continuation of the above point, as it generally only happens in complicated situations, but nevertheless GC is not the panacea-all-hail-the-mother-of-memory-leak-free-programming that the pundits claim it to be.  If programmers can&#8217;t be trusted to manage their own memory, and GC systems are easy to fool, what makes us think that programmers should be trusted to manage GC memory either?</li>
<li>Using GC is slow.  &#8220;What?!  Didn&#8217;t you say using GC is more efficient and leads to higher memory throughput?&#8221;  I did, but I was baiting a bit, because that&#8217;s what the propaganda says.  Yes using a good, modern, GC leads to higher throughput of memory allocs and frees, this is true.  What the GC evangelists don&#8217;t remind you of is that most [well designed] programs allocate a bunch of memory, use the same memory over and over again, and then release the memory, so most of a program&#8217;s time [usually] isn&#8217;t spent allocating and deleting.  If your GC app needs to run for a lengthy period of time, chances are the GC&#8217;s sweep phase is going to use up more processing power than would have been &#8220;wasted&#8221; on manually allocating your own memory.  Which leads me to the next point.</li>
<li>GC makes it easy to fall into bad programming habits.  This is a bit subjective, and obviously not true in all cases.  But in using a GC language I&#8217;ve noticed a tendency in myself to <b>new</b> things that shouldn&#8217;t necessarily be <b>new</b>ed.  Since I don&#8217;t have to worry about memory management the odd <b>new</b> here or there doesn&#8217;t really matter, right?  In a non-GC language I would certainly have created a temporary on the stack rather than allocate memory on the heap (which as we all know is orders of magnitude slower than a stack alloc &#8212; and it&#8217;s even worse in a GC scenario).  Basically think of any Java code you&#8217;ve ever seen&#8230; how many times have you seen something like: GridCell.setPosition(new Position(x, y)) inside a loop?  Ack!  Granted this is sort of unavoidable in Java, but especially for people who are still learning, this is a terrible habit to pick up.</li>
</ul>
<p>So given all of this, it sounds like I&#8217;m saying GC is complicated, slow, and makes you dumb.  But I&#8217;m not.  I still hold true to the notion that memory management is something a programmer shouldn&#8217;t often have to explicitly deal with.  GC is a good thing!  </p>
<p>But getting the whole story with garbage collection is important.  Like any tool, it&#8217;s one of those things that has good use cases and bad, and knowing where and when to use it is key.  Fortunately, in D&#8217;s case, it&#8217;s ridiculously easy to mix manual and GC memory management, so for me, it&#8217;s not that much of an issue.  I just get sick and tired of hearing the all-pro GC arguments, because in reality GC makes life for a programmer a little bit tougher.  And by tougher I mean that more knowledge is required to complete a task.</p>
<p>In the end though it&#8217;s definitely worth it.  GC might not get rid of memory leaks, and it&#8217;s probably going to make your program slightly less efficient, and it might even introduce a few &#8220;bad&#8221; habits, but in some cases these are reasonable trade offs.  If you know a temporary heap allocation is going to get collected right away, and you&#8217;re not in a tight loop or something, then why not let the GC do some work for you!  If using GC ends up leading to some complicated weak reference scheme, do it manually!  </p>
<p>Basically it comes down to the age old adage of: know your tools.  Garbage collection can save valuable development time by freeing a programmer from having to deal with the bulk of an application&#8217;s memory management, thus leaving more time to focus on those situations where you do need to get dirty with some mallocs and frees (or hopefully on things more interesting than memory management).  But, if used improperly, or in the wrong situation, it&#8217;s pretty easy for GC to end up causing more problems than it solves.</p>
]]></content:encoded>
			<wfw:commentRss>http://timburrell.net/blog/2008-03-06/garbage-collection-the-joy-and-the-curse/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
	</channel>
</rss>
