<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Freestyling on patterns, idioms and semantics...</title>
	<atom:link href="http://nicolabonelli.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://nicolabonelli.wordpress.com</link>
	<description>vivid hallucinations for bloodthirsty digital vampires</description>
	<lastBuildDate>Fri, 27 Jan 2012 14:00:44 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='nicolabonelli.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Freestyling on patterns, idioms and semantics...</title>
		<link>http://nicolabonelli.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://nicolabonelli.wordpress.com/osd.xml" title="Freestyling on patterns, idioms and semantics..." />
	<atom:link rel='hub' href='http://nicolabonelli.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Entangled_ptr: on the tension between pointers and move semantic</title>
		<link>http://nicolabonelli.wordpress.com/2011/04/30/entangled_ptr-on-the-tension-between-pointers-and-move-semantic/</link>
		<comments>http://nicolabonelli.wordpress.com/2011/04/30/entangled_ptr-on-the-tension-between-pointers-and-move-semantic/#comments</comments>
		<pubDate>Sat, 30 Apr 2011 17:11:17 +0000</pubDate>
		<dc:creator>Nicola</dc:creator>
				<category><![CDATA[c++]]></category>
		<category><![CDATA[C++0x]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://nicolabonelli.wordpress.com/?p=460</guid>
		<description><![CDATA[This installment digs into the tensions between raw pointers and the C++11 move semantic. The need of a new smart pointer is described and a novel design which supports the move semantic of both the pointer and the referred resource is presented. One of the most interesting addition of C++11 is the move semantic. It [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nicolabonelli.wordpress.com&amp;blog=17508&amp;post=460&amp;subd=nicolabonelli&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This installment digs into the tensions between raw pointers and the C++11 move semantic. The need of a new smart pointer is described and a novel design which supports the move semantic of both the pointer and the referred resource is presented. <span id="more-460"></span></p>
<p>One of the most interesting addition of C++11 is the move semantic. It enables an optimization which occurs in place of a copy when a given class supports it. In addition to this, when a class does not support moveability, the new semantic decays to a bare copy, so that the correctness of generic code is in any case not compromised.</p>
<p>Movability is enabled by the r-value reference. Declaring the move constructor and the move assignment operator for a given object is just enough to observe performance improvements in legacy codes (recompiled with a modern C++11 compiler). Only in few cases where l-value instances need to be moved, the additional use of the helper functions std::move is required.</p>
<p>While in real life the copy semantic is an abstract concept, the move semantic is very concrete one. An object can be moved from a point (a) to a point (b), by applying a force to it in accordance with the Newton&#8217;s Second Law. The provided work moves the object that is physically transfered to a different coordinate (the friction consumes the energy of the object, which, in turn comes to halt after a while the force is no longer applied). From the C++11 point of view, this concept is expressed by the following statement:</p>
<p><pre class="brush: cpp; gutter: false;">
Object b = std::move(a);
</pre></p>
<p>while a and b a are different instance located at different memory addresses, the meaning of such a statement is that the instance of the object (a) is now moved to the address of (b) (technically the internals of the object (a) are moved into the new object (b), but these details are beyond the scope of this essay).</p>
<p>Although the object (a) is valid after the move, it is left in a state only suitable for destruction or re-assignment. From the perspective of the client code, the object has been logically moved. The C++11 standard require, indeed, that the value of the object (b) is equivalent from that of the object (a) prior the move.</p>
<p>That said, any raw pointer referring to (a) it is to be considered &#8220;invalid&#8221;, in that even if it refers to an object only supposed to be destroyed (or reassigned, as suggested by Julien).</p>
<p><pre class="brush: cpp; gutter: false;">
std::vector vec;
Object * ptr = &amp;a;
vec.push_back(std::move(a));
// from now on ptr is no longer logically usable...
</pre></p>
<p>As shown in this example, It would be desirable to have ptr referring to the object moved inside the vector. To enable this, the pointer should be smart enough to detect when the resource has been logically moved at a different address and to be able to update its internals accordingly. It&#8217;s not the case of raw pointers anyway.</p>
<p><strong>The entangled_ptr&lt;&gt; class.</strong></p>
<p>more::entangled_ptr is a novel smart pointer class that enables tracking semantic. It is different from std::shared_ptr, in that its primary aim is not to manage the ownership of the allocated resource. Instead, the entangled_ptr is supposed to track objects while they are moved around by means of the move semantic.</p>
<p>For an object, in order to be track-able by an entangled_ptr, its class type must derive from the <strong>more::enable_entangled_from_this&lt;&gt;</strong>, much like a class must derives from std::enable_shared_from_this&lt;&gt; to be able to generates shared_ptr&lt;&gt; pointing to its instances.</p>
<p><pre class="brush: cpp; gutter: false;">
class Object : public more::enable_entangled_from_this&lt;Object&gt;
</pre></p>
<p>The Object class inherits the method <strong>entangled_from_this()</strong> which returns an entangled_ptr&lt;&gt; referring to the instance:</p>
<p><pre class="brush: cpp; gutter: false;">
Object instance;
auto ptr = instance.entangled_from_this();
</pre></p>
<p>From now on it&#8217;s possible to move the object around; the entaglet ptr will be tracking it!</p>
<p><pre class="brush: cpp; gutter: false;">
vec.push_back(std::move(instance));
ptr-&gt;method(); // it's still ok, the method is invoked on the instance moved into the vector.
</pre></p>
<p><strong>Implementing a track-able and move-able object.</strong></p>
<p><strong></strong>For an object to be track-able by an entangled_ptr, not only its class must derive from more::enable_entangled_from_this&lt;&gt;, but also it must be implementing the move constructor and the move assignment operator properly.</p>
<p><pre class="brush: cpp; gutter: false;">
    struct test : public more::enable_entangled_from_this&lt;test&gt;
    {
        test() = default;

        test(test &amp;&amp;rhs)
        : super(std::move(rhs))
        {
            ...
        }

        test&amp; operator=(test &amp;&amp;rhs)
        {
            super::operator=(std::move(rhs));
            ...
        }
</pre></p>
<p>It&#8217;s worth noting that the more::enable_entangled_from_this&lt;&gt; class type-defines itself as &#8216;super&#8217; in order to relax the typing required to invoke the move constructor and the move assignment operator of the base class. It is important to know that that such a class is non copyable because it would otherwise break the auto-referenced pointer semantic of the entangled_ptr, that must point to one resource at time.</p>
<p>The copy constructor and the assignment operator of the base class enable_entangled_from_this are deleted and, in turn, the class deriving from it is non copyable. A track-able object can be referenced by any number of entangled_ptr, which are instead copyable, as well as moveable. When a resources is moved at a different address, all the entangled_ptr referencing to it are updated accordingly.</p>
<p>The complete implementation of the <strong>more::entangled_ptr</strong> is available <a href="http://code.google.com/p/nicola-bonelli-repo/source/browse/trunk/codes.cpp0x/entangled_ptr.hpp">here</a>, along with a comprehensive <a href="http://code.google.com/p/nicola-bonelli-repo/source/browse/trunk/codes.cpp0x/entangled_ptr-test.cpp">test</a>. Enjoy C++11, always. Nicola</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nicolabonelli.wordpress.com/460/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nicolabonelli.wordpress.com/460/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nicolabonelli.wordpress.com/460/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nicolabonelli.wordpress.com/460/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nicolabonelli.wordpress.com/460/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nicolabonelli.wordpress.com/460/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nicolabonelli.wordpress.com/460/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nicolabonelli.wordpress.com/460/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nicolabonelli.wordpress.com/460/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nicolabonelli.wordpress.com/460/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nicolabonelli.wordpress.com/460/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nicolabonelli.wordpress.com/460/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nicolabonelli.wordpress.com/460/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nicolabonelli.wordpress.com/460/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nicolabonelli.wordpress.com&amp;blog=17508&amp;post=460&amp;subd=nicolabonelli&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nicolabonelli.wordpress.com/2011/04/30/entangled_ptr-on-the-tension-between-pointers-and-move-semantic/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5befef1a4026910d0fd53c2dcf63bf6d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">nicolabonelli</media:title>
		</media:content>
	</item>
		<item>
		<title>Introducing PFQ&#8230;</title>
		<link>http://nicolabonelli.wordpress.com/2011/04/24/introducing-pfq/</link>
		<comments>http://nicolabonelli.wordpress.com/2011/04/24/introducing-pfq/#comments</comments>
		<pubDate>Sun, 24 Apr 2011 08:39:13 +0000</pubDate>
		<dc:creator>Nicola</dc:creator>
				<category><![CDATA[linux]]></category>
		<category><![CDATA[networking]]></category>
		<category><![CDATA[kernel]]></category>

		<guid isPermaLink="false">http://nicolabonelli.wordpress.com/?p=416</guid>
		<description><![CDATA[PFQ is a novel linux kernel module designed for packet capturing on multicore architectures. After 2 months of hard work I&#8217;m proud to unveil the first results. Even if the software is still in its infancy the performance is one of its strength. PFQ is capable of capturing million packets per second running on a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nicolabonelli.wordpress.com&amp;blog=17508&amp;post=416&amp;subd=nicolabonelli&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>PFQ is a novel linux kernel module designed for packet capturing on multicore architectures. After 2 months of hard work I&#8217;m proud to unveil the first results. Even if the software is still in its infancy the performance is one of its strength.</p>
<p><span id="more-416"></span></p>
<p>PFQ is capable of capturing million packets per second running on a commodity Xeon processor, equipped with an Intel 82599 10G network adapter.</p>
<p>The graph shows how well PFQ scales with the number of cores. The performance scales linearly up to the number of physical cores involved in the capturing process, 6 in my case. The second 6 cores are in reality virtual cores, rendered by the Intel hyper-threading machinery.</p>
<div id="attachment_506" class="wp-caption aligncenter" style="width: 416px"><a href="http://nicolabonelli.files.wordpress.com/2011/04/n-threads.png"><img class="size-full wp-image-506 " title="PFQ: n-capturing threads" src="http://nicolabonelli.files.wordpress.com/2011/04/n-threads.png?w=406&#038;h=310" alt="" width="406" height="310" /></a><p class="wp-caption-text">PFQ capturing system</p></div>
<p>My testbed shows that PFQ can capture and copy to userspace up to <del datetime="2011-05-19T11:12:52+00:00">10 Million</del> 12.5 Millions (42 Millions with copies) packets per seconds (64-bytes long) by deploying 6 cores @2.66Ghz in the capturing process and the multi-queue Intel 82599 ethernet adapter.</p>
<p>With a recent optimization, the CPU load-average is about <del datetime="2011-05-19T10:44:59+00:00">25% (per core)</del> 15% per core. In comparison, the PF_PACKET socket, when used in memory map mode as in pcap library, can capture no more than few hundred thousand or so packets per second.</p>
<p>The PFQ source code is available for download at github: <a title="PFQ" href="https://github.com/pfq">https://github.com/pfq</a>!</p>
<p>Enjoy!</p>
<p>Nicola</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nicolabonelli.wordpress.com/416/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nicolabonelli.wordpress.com/416/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nicolabonelli.wordpress.com/416/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nicolabonelli.wordpress.com/416/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nicolabonelli.wordpress.com/416/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nicolabonelli.wordpress.com/416/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nicolabonelli.wordpress.com/416/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nicolabonelli.wordpress.com/416/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nicolabonelli.wordpress.com/416/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nicolabonelli.wordpress.com/416/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nicolabonelli.wordpress.com/416/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nicolabonelli.wordpress.com/416/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nicolabonelli.wordpress.com/416/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nicolabonelli.wordpress.com/416/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nicolabonelli.wordpress.com&amp;blog=17508&amp;post=416&amp;subd=nicolabonelli&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nicolabonelli.wordpress.com/2011/04/24/introducing-pfq/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5befef1a4026910d0fd53c2dcf63bf6d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">nicolabonelli</media:title>
		</media:content>

		<media:content url="http://nicolabonelli.files.wordpress.com/2011/04/n-threads.png" medium="image">
			<media:title type="html">PFQ: n-capturing threads</media:title>
		</media:content>
	</item>
		<item>
		<title>IoC revisited: from callback to closure!</title>
		<link>http://nicolabonelli.wordpress.com/2010/11/01/ioc-revisited-from-callback-to-closure/</link>
		<comments>http://nicolabonelli.wordpress.com/2010/11/01/ioc-revisited-from-callback-to-closure/#comments</comments>
		<pubDate>Mon, 01 Nov 2010 15:08:04 +0000</pubDate>
		<dc:creator>Nicola</dc:creator>
				<category><![CDATA[c++]]></category>
		<category><![CDATA[C++0x]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://nicolabonelli.wordpress.com/?p=281</guid>
		<description><![CDATA[I have been told to consider the IoC pattern for this series and I decided to explore it because I was not really familiar with this pattern. Wikipedia defines IoC (Inversion of Control) as an abstract principle that describes an aspect of some software architecture design in which the flow control of a system is [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nicolabonelli.wordpress.com&amp;blog=17508&amp;post=281&amp;subd=nicolabonelli&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I have been told to consider the IoC pattern for this series and I decided to explore it because I was not really familiar with this pattern.</p>
<p>Wikipedia defines IoC (Inversion of Control) as an abstract principle that describes an aspect of some software architecture design in which the flow control of a system is inverted in comparison to procedural programming. According to Martin Fowler, the term IoC is at least dated 1988, but, it&#8217;s still unclear whether it can be considered a pattern or just an architectural principle.</p>
<p><span id="more-281"></span></p>
<p>Although IoC is a generic principle, concrete implementations depend on the semantics in play. Indeed, in the everyday C++ programming, IoC can be found in different forms. Among them:</p>
<ul>
<li>Pointer to functions (callback)</li>
<li>Generic Programming: STL algorithms, functors and callable objects</li>
<li>Polymorphism and NVI idiom</li>
<li>Policy Classes</li>
<li>Strategy pattern and std::function</li>
<li>Lamba functions and closures</li>
</ul>
<p>The listed idioms differ each other, but the principle on which they are based is common: to provide a means for customizing an algorithm, improving both software decoupling and code reusability. In particular, the principle focuses on the separation between the code implementation and the execution.</p>
<p>In this essay we will examine different idioms, pointing out the properties that each one has in common with the IoC principle. In doing so, we will put emphasis on some possible implementations with respect to the C/C++ and the upcoming C++0x language.</p>
<h3><strong>Pointers to function</strong></h3>
<p><em>Pointer to function</em> is the more ancient means that implements IoC. Even if most modern programming language got ride of them, pointers are supported by both C and C++ language and today still represent a valuable programming element.</p>
<p>Pointer to functions allow to customize a generic algorithm by means of callbacks. As an example the  GNU C library, which provides functions for searching and sorting arrays of arbitrary objects.</p>
<p>Let&#8217;s examine qsort:</p>
<p><strong>qsort</strong> (<var>void *array, size_t count, size_t size, comparison_fn_t compare</var>)</p>
<p>The third argument, <em>comparison_fn_t</em> type, defined as &#8220;int comparison_fn_t (const void *, const void *)&#8221;, is the signature of the callback. The client code is supposed to provide a congruent comparison function in order to specialize the sort algorithm. For example:</p>
<p><pre class="brush: cpp; gutter: false;">
     int
     compare_doubles (const void *a, const void *b)
     {
       const double *da = (const double *) a;
       const double *db = (const double *) b;

       return (*da &gt; *db) - (*da &lt; *db);
     }
</pre></p>
<p>The advantage of pointers to function in comparison to other semantics is the ability to customize an algorithm with a callback whose address can even be unknown at compile time (for example with functions dynamically loaded at run time from a shared library). The other side of the coin is that this feature results in a performance penalty, a major drawback if compared to other mechanism provided by  C++ and templates.</p>
<h3>Generic Programming: STL algorithms, functors and callable types.</h3>
<p>One of the big wins of C++ over C is represented by the templates, a semantic that enables generic programming. The Standard Template Library today is an exceptional example we all have something to learn from. More importantly, not only is it possible to customize generic STL algorithms by means of function pointers, but also it is possible to pass callable objects at the instantiation point (instances of callable types).</p>
<p>A <em>callable type</em> is defined as:</p>
<ul>
<li>a pointer to function</li>
<li>a pointer to member function</li>
<li>a pointer to member data</li>
<li>a class type whose objects can stand at the left-hand side of a function call operator, that is a class that implements the operator() or a conversion to a pointer to function.</li>
</ul>
<p>At the instantiation point, there&#8217;s no difference between passing a function pointer or an instance of a callable object as argument to a template function.</p>
<p><pre class="brush: cpp; gutter: false;">
    template &lt;typename Fun&gt;
    void algorithm(Fun f)
    {
        f(arg1, arg2, ...);
    }
</pre></p>
<p>The function algorithm can either take a pointer to function or an instance of a callable type: both must have a matching signature.</p>
<p>A classic callable object is represented by functor, that is a class that implements the operator():</p>
<p><pre class="brush: cpp; gutter: false;">
    struct generic_functor
    {
        void operator()(int arg1, arg arg2, ....) const
        {
           ...
        }
    };
</pre></p>
<p>Unlike a pointer to function, a functor can have a private state that can be accessed across different executions. Unfortunately, the standard does not specify that the STL algorithms must not make internal copies of the passed functors. As a result, the client code cannot take advantage of this, and this reason explains why the instances of callable types are usually passed to algorithms as temporary objects. Yet, passing a functor by std::ref() may lead to wrong results, if later we expect to find a consistent state as it were never copied.</p>
<p>The sole exception to this is represented by std::for_each algorithm, which returns a copy of the callable object in order to expose to the client code the state of the object utilized during the iteration. std::for_each guarantees that the instance of the function used during the iteration is unique.</p>
<p><pre class="brush: cpp; gutter: false;">
    generic_functor out = std::for_each(vec.begin(), vec.end(), generic_functor());
</pre></p>
<p>In term of performance, there&#8217;s an important difference between calling a pointer to function and invoking a functor. In particular, the code of the operator() can be inlined into the algorithm, while the code of a function referred by a pointer can&#8217;t be because the value of the pointer is known at runtime (even if in some cases it could be statically determined at compile time).</p>
<p>The C++ standard provides a rich set of functors in the  header &lt;functional&gt;. Among them, std::greater&lt;&gt; and std::less&lt;&gt; predicates that can be used to customize algorithms with different way to compare objects. For example, it&#8217;s possible to customize the std::sort in order to obtain a vector of integers sorted into descending order:</p>
<p><pre class="brush: cpp; gutter: false;">
    std::sort( vec.begin(), vec.end(), std::greater&lt;int&gt;());
</pre></p>
<h3>Polymorphism and NVI idiom</h3>
<p>Another important lesson to learn from STL is that virtual functions should never be declared public. This principle, known as NVI idiom (Non Virtual Interface) or &#8220;the template method&#8221;, enables pre-condition and post-condition checking of virtual functions.</p>
<p>The NVI idiom, behind his back, can used to implement the IoC principle on the top of the inheritance polymorphism. The idea is simple: the base class exposes public methods implemented in term of the protected virtual functions provided, in turn, by the concrete class.</p>
<p>One important example of NVI idiom is, for example, the <em>std::streambuf class</em>, a class provided by the standard library to implement user-defined stream buffers. Streambufs are meant to customize the <em>std::stream </em>class, in order to accomplish the operations of read and write of character sequences.</p>
<p>As an example, my membuf class, a streambuf that can be used to stream from/to in-memory buffers:</p>
<p><pre class="brush: cpp; gutter: false;">
    struct membuf : public std::streambuf
    {
        membuf(char *buffer, size_t size)
        {
            this-&gt;setp(buffer,buffer+size);
            this-&gt;setg(buffer,buffer,buffer+size);
        }

        char *end()
        {
            return this-&gt;pptr();
        }
    };
</pre></p>
<h3>Policy class</h3>
<p>Policy-based class design was first presented by Andrei Alexandrescu in the book Modern C++ Design. To repeat his words, the policy class is a technique that enables the creation of flexible, highly reusable template libraries. Such a design enables the separation of the implementation from the generic aspects of a class, increasing software decoupling, especially when multiple policies are concurrently deployed.</p>
<p>A policy-class can be, but it&#8217;s not limited to, a struct containing static methods that embody the details of the implementation. The classes that belong to the same policy are syntax oriented, and must respect the interface defined by the policy itself. Whether the policy-class or the included methods are templated, instead, is a matter of implementation.</p>
<p>A template class based on policy-classes is called <em>host class </em>and it&#8217;s where the magic of IoC happens. Policy-classes are passed to the host in different manners: as a template argument if the policy class includes only static methods, by means of inheritance otherwise.</p>
<p>Such a host class takes advantage of the implementations provided by the policy-classes at its instantiation point. Unlike the NVI, which is implemented by means of polymorphic inheritance, the <em>host class </em>enables IoC with no performance penalty, thanks to the static methods mixed-in by templates or by the non-polymorphic inheritance (the policy class has no virtual functions).</p>
<p>The policy class is similar to a traits class and differs from it only in that it&#8217;s more focused on the behavior rather than on the properties of the type. Also, the policy-class revamps the implementation of the Strategy pattern with compile-time bindings.</p>
<p>The C++ standard has an important example of policy-class: the <strong>std::char_traits, </strong>which is used to customize the behavior of the<strong> std::basic_string. </strong>Despite the name, indeed, char_tratits is a policy class rather than a traits class.<strong><br />
</strong></p>
<h3>Strategy pattern and std::function</h3>
<p>The strategy pattern is a particular design where the algorithms to run is dynamically selected. It is the ancestor of the policy-class: it provides the same functionality, with the difference that the binding with strategies happens at runtime, while the binding with policies does at compile time.</p>
<p>While different implementations are possible, the most convenient one is by means of  C++0x  <strong>std::function</strong>(or std::tr1::function available with C++03)<strong>. </strong>Strategies, indeed, can be implemented with pointers to function or by means of polymorphic functors (with a common interface).</p>
<p>The std::function extends the strategy pattern with the ability to capture any kind of callable object with a consistent signature. The std::function allows to pass a function pointer to the strategy that later can be replaced with an instance of a callable object. All of this is possible thanks to the <em>type erasure</em> mechanism, a technique buried inside its implementation.</p>
<p>An example of a strategy-based class is:</p>
<p><pre class="brush: cpp; gutter: false;">
    class strategy_based_class
    {
        typedef std::function fun_type;

        void set_compare(const fun_type &amp;cmp)
        { _M_compare = cmp;}

        fun_type get_compare() const
        { return _M_compare; }

        void algorithm()
        {        ....
             if(_M_compare(a,b)) {
                 ....
             }
        }

    private:
        fun_type _M_compare;
    };
</pre></p>
<p>Like the other idioms, the use of std::function can be interpreted as an implementation the IoC principle: the stategy class can focus on the execution rather than on the implementation, demanded to the std::function itself.</p>
<h3>Lambda functions and closures</h3>
<p>The C++0x introduces a new kind of callable type, directly implemented in the core language: the lambda function. However, lambdas are not a real news in the C++ language. The boost library already implemented it (on the top of c++03) by means of the magic template metaprogramming.</p>
<p>Lambdas are a means to implement anonymous functions that can be declared inline, right where you need them. It&#8217;s possible to declare a lambda at the instantiation point of a generic algorithm, without the need to declare the callable type with global visibility. The use of lamba functions is very handy and effective.</p>
<p>Lambdas have also the ability to refer to identifiers declared outside the lambda itself, much like the nested functions of the C language. A lambda function that access to external variables is known as closure, in honor to the Lips language.</p>
<p>With respect to IoC, lambdas are just another way to customize a template function/algorithm, like those of STL, and they are also assignable to a std::function&lt;&gt; with a compatible signature.</p>
<p>As examples, the std::sort of a container in descending order and the accumulate algorithm, implemented by std::for_each, both in term of lambda functions.</p>
<p><pre class="brush: cpp; gutter: false;">
    std::sort(vec.begin(), vec.end(), [](int a, int b) { return a &gt; b; });
</pre></p>
<p>and</p>
<p><pre class="brush: cpp; gutter: false;">
    int sum = 0;
    std::for_each(vec.begin(), vec.end(), [&amp;sum](int n) { sum += n; });
</pre></p>
<p>The original article of Martin Folwer covers more detailed aspects of IoC, especially from the point of view of the Java language.  Also more information can be obtained at ﻿<a href="http://martinfowler.com/bliki/InversionOfControl.html">http://martinfowler.com/bliki/InversionOfControl.html</a>.</p>
<p>In this essay I covered the IoC pattern, presenting some implementations from the point of view of the expressive C++ language. While the acronym IoC is not so common in the C++ world, its meaning can be found in very different forms: it&#8217;s a matter to distinguish it in a plethora of semantics.</p>
<p>Enjoy C++0x, always.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nicolabonelli.wordpress.com/281/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nicolabonelli.wordpress.com/281/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nicolabonelli.wordpress.com/281/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nicolabonelli.wordpress.com/281/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nicolabonelli.wordpress.com/281/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nicolabonelli.wordpress.com/281/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nicolabonelli.wordpress.com/281/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nicolabonelli.wordpress.com/281/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nicolabonelli.wordpress.com/281/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nicolabonelli.wordpress.com/281/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nicolabonelli.wordpress.com/281/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nicolabonelli.wordpress.com/281/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nicolabonelli.wordpress.com/281/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nicolabonelli.wordpress.com/281/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nicolabonelli.wordpress.com&amp;blog=17508&amp;post=281&amp;subd=nicolabonelli&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nicolabonelli.wordpress.com/2010/11/01/ioc-revisited-from-callback-to-closure/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5befef1a4026910d0fd53c2dcf63bf6d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">nicolabonelli</media:title>
		</media:content>
	</item>
		<item>
		<title>Variadic Metafunctions</title>
		<link>http://nicolabonelli.wordpress.com/2010/10/22/variadic-metafunctions/</link>
		<comments>http://nicolabonelli.wordpress.com/2010/10/22/variadic-metafunctions/#comments</comments>
		<pubDate>Fri, 22 Oct 2010 22:49:21 +0000</pubDate>
		<dc:creator>Nicola</dc:creator>
				<category><![CDATA[C++0x]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://nicolabonelli.wordpress.com/?p=217</guid>
		<description><![CDATA[An interesting use of variadic template arguments [VTA] comes used with metaprogramming: it results in a metafunction that takes a variable number of arguments. For those who have never heard about metafuncions I would suggest to read a couple of books,  C++ Modern Design Pattern and the more specific C++ Template Metaprogramming. To make the long story [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nicolabonelli.wordpress.com&amp;blog=17508&amp;post=217&amp;subd=nicolabonelli&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>An interesting use of variadic template arguments [VTA] comes used with metaprogramming: it results in a metafunction that takes a variable number of arguments.</p>
<p>For those who have never heard about <a href="http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Metafunction">metafuncions</a> I would suggest to read a couple of books,  <a href="http://www.amazon.com/Modern-Design-Generic-Programming-Patterns/dp/0201704315">C++ Modern Design Pattern</a> and the more specific <a href="http://www.boostpro.com/mplbook/">C++ Template Metaprogramming</a>. To make the long story short,  a metafunction is a function that runs at compile time. The technique was discovered by Erwin Unruh  years ago when he created a C++ program that, though not compiling, was able to generate the sequence of prime numbers in form of  compiler error messages.</p>
<p><span id="more-217"></span></p>
<p>Today metaprogramming has become a very refined technique widely exploited in a number of C++ template libraries, boost to mention one. A didactic example of a numeric metafunction is the factorial:</p>
<p><pre class="brush: cpp; gutter: false;">
template &lt;int N&gt;
struct factorial
{
    enum { value = N * factorial::value };
};

template &lt;&gt;
struct factorial&lt;0&gt;
{
    enum { value = 1 };
};

</pre></p>
<p>An important achievement of the last years, presented by Alexandrescu in Modern Design Pattern, is the type list, that is a recursive agglomerate of types that resembles to a list of types. The type list enables implementations of different classes, tuple and variant to mention a few.</p>
<p>A possible implementation of a type list is the following one:</p>
<p><pre class="brush: cpp; gutter: false;">
struct null {}; // typelist terminator

template &lt;typename H, typename T&gt;
struct typelist {};

typedef typelist&lt; int, typelist&lt; char, typelist&lt; short, null&gt; &gt; &gt; list_type; // list of int, char and short
</pre></p>
<p>&#8230;where the null type is a placeholder that identifies the end of the list. The list itself (list_type) is just a type. Therefore, to operate on it a set of metafunctions is required.</p>
<p>For instance, the following metafunction can be used to calculate the length of such a type list:</p>
<p><pre class="brush: cpp; gutter: false;">
    // length&lt;Tp&gt;::value
    //

    template &lt;typename Tp&gt; struct length;
    template &lt;&gt;
    struct length&lt;null&gt;
    {
        enum { value = 0 };
    };

    template &lt;typename T,typename U&gt;
    struct length&lt; typelist&lt;T,U&gt; &gt;
    {
        enum { value = 1 + length&lt;U&gt;::value };
    };
</pre></p>
<p>By means of templates and recursion it is possible to implement a complete set of meta-functions, like adding a type to the head, to the tail and so forth.</p>
<p>However, VTA allows to express the type-list in a better way and in this essay I present a possible novel implementation along with some variadic companion metafunctions.</p>
<p>That said, a new definition of a typelist could be the following one:</p>
<p><pre class="brush: cpp; gutter: false;">
    template &lt;typename ...Ti&gt;
    struct type_list {};
</pre></p>
<p>It follows that the declaration of a type-list looks like this:</p>
<p><pre class="brush: cpp; gutter: false;">
    type_list&lt;int, char, double&gt;
</pre></p>
<p>which is very compact declaration in comparison to those enabled by means of C++03, that in the best case use some preprocessing macros to hide the boilerplate declaration.</p>
<p>This new list requires variadic metafunctions to perform operations on it. For instance, the metafunction that calculates the length of such a list is the following one:</p>
<p><pre class="brush: cpp; gutter: false;">
    // length&lt;&gt;::value
    //
    template &lt;typename Tl&gt; struct length;

    template &lt;typename T, typename ...Ti&gt;
    struct length&lt;typelist&lt;T, Ti...&gt;&gt;
    {
        enum { value = 1 + length&lt;typelist&lt;Ti...&gt;&gt;::value };
    };

    template &lt;typename T&gt;
    struct length&lt;typelist&lt;T&gt;&gt;
    {
        enum { value = 1 };
    };

    template &lt;&gt;
    struct length&lt;typelist&lt;&gt;&gt;
    {
        enum { value = 0 };
    };
</pre></p>
<p>A better non-recursive implementation is based on the sizeof&#8230;() operator that, when applied to a parameter pack, returns the number of the elements.</p>
<p><pre class="brush: cpp; gutter: false;">
    template &lt;typename Tl&gt; struct length;
    template &lt;typename ...Ti&gt;
    struct length&lt;typelist&lt;Ti...&gt;&gt;
    {
        enum { value = sizeof...(Ti) };
    };
</pre></p>
<p>It&#8217;s worth noting that by means of  VTA the implementation of meta-functions like insert and append result much simple:</p>
<p><pre class="brush: cpp; gutter: false;">
    // append&lt;&gt;::type
    //
    template &lt;typename Tl, typename Tp&gt; struct append;
    template &lt;typename Tp, typename ...Ti&gt;
    struct append&lt;typelist&lt;Ti...&gt;, Tp&gt;
    {
        typedef typelist&lt;Ti...,Tp&gt; type;
    };

    // insert&lt;&gt;::type
    //
    template &lt;typename Tl, typename Tp&gt; struct insert;
    template &lt;typename Tp, typename ...Ti&gt;
    struct insert&lt;typelist&lt;Ti...&gt;, Tp&gt;
    {
        typedef typelist&lt;Tp, Ti...&gt; type;
    };
</pre></p>
<p>The other companion functions that a typelist should be implementing are not provided herein. I leave the reader with the pleasure to implement them as a brain teaser. All in all, an important part of coding is the fun.</p>
<p>Enjoy the C++0x, always!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nicolabonelli.wordpress.com/217/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nicolabonelli.wordpress.com/217/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nicolabonelli.wordpress.com/217/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nicolabonelli.wordpress.com/217/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nicolabonelli.wordpress.com/217/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nicolabonelli.wordpress.com/217/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nicolabonelli.wordpress.com/217/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nicolabonelli.wordpress.com/217/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nicolabonelli.wordpress.com/217/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nicolabonelli.wordpress.com/217/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nicolabonelli.wordpress.com/217/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nicolabonelli.wordpress.com/217/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nicolabonelli.wordpress.com/217/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nicolabonelli.wordpress.com/217/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nicolabonelli.wordpress.com&amp;blog=17508&amp;post=217&amp;subd=nicolabonelli&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nicolabonelli.wordpress.com/2010/10/22/variadic-metafunctions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5befef1a4026910d0fd53c2dcf63bf6d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">nicolabonelli</media:title>
		</media:content>
	</item>
		<item>
		<title>The Cool Factor(y)</title>
		<link>http://nicolabonelli.wordpress.com/2010/10/03/cool_factory/</link>
		<comments>http://nicolabonelli.wordpress.com/2010/10/03/cool_factory/#comments</comments>
		<pubDate>Sun, 03 Oct 2010 15:39:42 +0000</pubDate>
		<dc:creator>Nicola</dc:creator>
				<category><![CDATA[c++]]></category>
		<category><![CDATA[C++0x]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://nicolabonelli.wordpress.com/?p=95</guid>
		<description><![CDATA[With the coming of C++0x our previous C++ codes seem to have become too boilerplate. Among the number of important changes and improvements over the core language, the one I like most is the variadic template argument, a new semantic that enables the variable number of template arguments for both template classes and functions. In [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nicolabonelli.wordpress.com&amp;blog=17508&amp;post=95&amp;subd=nicolabonelli&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>With the coming of C++0x our previous C++ codes seem to have become too boilerplate. Among the number of important changes and improvements over the core language, the one I like most is the variadic template argument, a new semantic that enables the variable number of template arguments for both template classes and functions.</p>
<p>In turn, the variadic template arguments [VTA], ﻿along with the r-value reference that allows the perfect forwarding, enable users to design very compact patterns with a high level of code re-usability, opening the doors to a new way of writing generic code.</p>
<p><span id="more-95"></span></p>
<p>Up until now, we have emulated VTA by replicating the source code of a class or function, providing the implementation for each number of arguments we wanted it to support. A more elegant way consisted in writing a single generic function (or class) accepting the maximum number of template arguments and providing a placeholder type, like struct null {},  to pad the unused arguments.</p>
<p>These solutions provided the users with the illusion of using VTA on the top of C++03, while leaving the effort of maintaining the boilerplate code to the library implementers, tempted to support a few numbers of arguments, typically four or five (uhm, I&#8217;m lazy).</p>
<p>VTAs on the top of C++0x are of a great help when it comes to implement a design pettern. The factory pattern is not an exception.</p>
<p>The <a href="http://en.wikipedia.org/wiki/Factory_method_pattern">factory</a> is a very common pattern. If you have written about a thousand of code lines in your life, probably about 5% of them represent a factory. This pattern is also known as <a href="http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Virtual_Constructor">virtual-constructor idiom</a> since it implements a polymorphic generic constructor driven by runtime values. </p>
<p>Some of the valuable points of the factory are listed below:</p>
<ul>
<li>it&#8217;s generic and can be reused (the extent of reusabiliy depends on the implementation&#8230;)</li>
<li>it makes the code clean and extensible (without changing a single line in the client code)</li>
</ul>
<p>If It&#8217;s true that for a library the implementation matters, for a reusable pattern it&#8217;s even more important. Basically the implementation of a factory I&#8217;m going to present consists in an associative container (a standard map) that maps an identifier into a polymorphic factory allocator, that is a template class in charge of allocating the concrete type, providing the arguments to its constructor.</p>
<p>Compared to the virtual constructor idiom of  <a href="http://www.amazon.com/Advanced-C-Programming-Styles-Idioms/dp/0201548550">Coplien</a> this implementation does not make use of exemplars and that has an evident advantage in term of resource consumption: instances of elements are built on demand and not virtually cloned, nor copy-constructed! That&#8217;s a good point because exemplars may acquire resources only released at the factory destruction, or yet they may be not copyable/cloneable at all (because, for instance, just moveable).</p>
<p>In order to exploit the polymorphism the two classes <strong>factory_base_allocator</strong> and the generic <strong>factory_allocator</strong> are implemented in a IS-A relation:</p>
<p><pre class="brush: cpp; gutter: false;">
template &lt;typename B, typename ... &gt;
struct factory_base_allocator
{
    virtual ~factory_base_allocator()
    {}

    virtual B * alloc(Arg&amp;&amp; ... ) = 0;
};

template &lt;typename B, typename D, typename ... &gt;   // B is a base class of D
struct factory_allocator : public factory_base_allocator&lt;B,Arg...&gt;
{
    static_assert(std::is_base_of&lt;B,D&gt;::value, &quot;base_of relationship violated&quot;);

    virtual D * alloc(Arg &amp;&amp;... arg)
    {
        return new D(std::forward&lt;Arg&gt;(arg)...);
    }
};
</pre></p>
<p>The factory_base_allocator is a template class: the generic type B is the common base of all the types for whom the factory is the manger. The argument pack Arg is the list of types to be passed to the constructor of the concrete class. Arguments are taken by r-value reference and perfectly forwarded the proper constructor by means of the <em>std::forward, </em>an utility in charge to fix the argument deduction type: r-value if the provided argument is an r-value, l-value otherwise.</p>
<p>The factory_allocator ensures that the type D of the concrete class is in a IS-A  relation with the generic base class (B) my means of the type_trait <strong>std:::is_base_of&lt;&gt; </strong>and the valuable <strong>static_assert. </strong>This utility class implements the sole virtual method <strong>alloc</strong> supposed to construct the instance of D on demand.</p>
<p>Enjoy for a while the beauty of the virtual variadic method <strong>alloc</strong>: It implements a virtual perfect forwarder, a proof that that the implementation matters!</p>
<p>On the basis of this helper allocator, the implementation of the factory class results:</p>
<p><pre class="brush: cpp; gutter: false;">
    template &lt;typename K, typename T, typename ... Arg&gt;
    class factory
    {
    public:
        typedef std::map&lt;K, std::shared_ptr&lt;factory_base_allocator&lt;T,Arg...&gt;&gt;&gt; map_type;

        factory()  = default;
        ~factory() = default;

        bool
        regist(const K &amp; key, factory_base_allocator&lt;T,Arg...&gt; * value)
        { return _M_map.insert( make_pair(key, std::shared_ptr&lt;factory_base_allocator&lt;T,Arg...&gt; &gt;(value) ) ).second; }

        bool
        unregist(const K &amp;key)
        { return _M_map.erase(key) == 1; }

        bool
        is_registered(const K &amp;key) const
        {
            return _M_map.count(key) != 0;
        }

        template &lt;typename ... Ti&gt;
        std::shared_ptr&lt;T&gt;
        operator()(const K &amp;key, Ti&amp;&amp; ... arg) const
        {
            auto it = _M_map.find(key);
            if (it == _M_map.end())
                return std::shared_ptr&lt;T&gt;();
            return std::shared_ptr&lt;T&gt;(it-&gt;second-&gt;alloc(std::forward&lt;Ti&gt;(arg)...));
        }

    private:
        map_type _M_map;
    };
</pre></p>
<address></address>
<address><span style="font-style:normal;">The complete source code is available <a href="http://code.google.com/p/nicola-bonelli-repo/source/browse/trunk/codes.cpp0x/factory.hpp">here</a>.</span></address>
<address><span style="font-style:normal;"><br />
</span></address>
<address><span style="font-style:normal;"><br />
Enjoy the C++0x, always.</span></address>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nicolabonelli.wordpress.com/95/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nicolabonelli.wordpress.com/95/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nicolabonelli.wordpress.com/95/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nicolabonelli.wordpress.com/95/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nicolabonelli.wordpress.com/95/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nicolabonelli.wordpress.com/95/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nicolabonelli.wordpress.com/95/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nicolabonelli.wordpress.com/95/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nicolabonelli.wordpress.com/95/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nicolabonelli.wordpress.com/95/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nicolabonelli.wordpress.com/95/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nicolabonelli.wordpress.com/95/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nicolabonelli.wordpress.com/95/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nicolabonelli.wordpress.com/95/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nicolabonelli.wordpress.com&amp;blog=17508&amp;post=95&amp;subd=nicolabonelli&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nicolabonelli.wordpress.com/2010/10/03/cool_factory/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5befef1a4026910d0fd53c2dcf63bf6d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">nicolabonelli</media:title>
		</media:content>
	</item>
		<item>
		<title>Singleton: a mirage of perfection</title>
		<link>http://nicolabonelli.wordpress.com/2009/06/04/singleton-a-mirage-of-perfection/</link>
		<comments>http://nicolabonelli.wordpress.com/2009/06/04/singleton-a-mirage-of-perfection/#comments</comments>
		<pubDate>Thu, 04 Jun 2009 17:36:01 +0000</pubDate>
		<dc:creator>Nicola</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[c++0x]]></category>
		<category><![CDATA[c/c++]]></category>

		<guid isPermaLink="false">http://nicolabonelli.wordpress.com/?p=39</guid>
		<description><![CDATA[There are a very few lucky girls on earth who have had the pleasure to read the great and yet so chemically romantic book “Modern C++ Design: Generic Programming and Design Pattern Applied“. But if you are not one of them, don&#8217;t worry: it really does not matter. In that book there is an entire [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nicolabonelli.wordpress.com&amp;blog=17508&amp;post=39&amp;subd=nicolabonelli&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>There are a very few lucky girls on earth who have had the pleasure to read the great and yet so chemically romantic book “<a rel="#someid0" href="http://www.amazon.com/gp/product/0201704315/ref=yml_dp">Modern C++ Design: Generic Programming and Design Pattern Applied</a>“. But if you are not one of them, don&#8217;t worry: it really does not matter.</p>
<p>In that book there is an entire chapter devoted to present a whirl of singleton patterns that Andrei Alexandrescu gracefully dissects with his fervid insight of the out most boundaries of the C++ language. Andrei presents a unique, portable, <a href="http://en.wikipedia.org/wiki/Policy-based_design">policy-based</a> pattern (also implemented in his <a rel="#someid1" href="http://loki-lib.sourceforge.net/">Loki library</a>) which aims at covering most features required to build a perfect Singleton.</p>
<p>What? A singleton? Uhmkay, let’s rewind the tape.</p>
<p><span id="more-39"></span></p>
<p>A <a rel="#someid2" href="http://en.wikipedia.org/wiki/Singleton_pattern">Singleton</a>, as wikipedia reports, is a design pattern used to restrict instantiation of a class to one object. The usefulness of this pattern has been largely discussed: some consider the singleton a good pattern while others simply an anti-pattern because of the resource decoupling effect which it leads to.</p>
<p><span style="background-color:#ffffff;">That said, this essay is not meant to eulogize pros and cons of the singleton (after all it would be just a religious war). Instead some achievements of Anadrei are summarized and a candidate for a C++ implementation of the perfect singleton is discussed from the perspective of the GNU compiler.</span></p>
<p>In his book Andrei addresses two major issues that affect the popular singleton implementations: The <a href="http://en.wikipedia.org/wiki/Thread-safe">thread-safety</a> and the dead reference problem.</p>
<p>Concerning the thread safety, the singleton pattern is supposed to guarantee the uniqueness of  the instance, even among different threads. As a result, if a singleton implementation makes use of the <a rel="#someid3" href="http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.14">construction-on-the-first-use</a> idiom (which returns a local static instance), a locking mechanism is required to prevent threads from constructing multiple instances at the first concurrent access.</p>
<p>That said, the responsibility to build a unique instance goes to the singleton implementation, while the rest of thread-safe constraints are of course up to the class writer. As corner case you may consider a singleton class with no mutable members that returns a const reference to the unique instance. The critical part of such an implementation is the construction, since the subsequent accesses are not required to be atomic at all (the object is constant).</p>
<p>For this issue Andrei presents two popular patterns: the locking singleton (faulty because of the implicit race condition) and the <a rel="#someid4" href="http://en.wikipedia.org/wiki/Double-checked_locking">double-checked locking</a> singletons (Douglas Schmidt) which aims at fixing the former race but that under certain architecture/compiler is still faulty (memory barriers are required to carry out a correct double-checked singleton pattern).</p>
<p>The second issue addressed is the dead reference problem. Basically the problem is related to the order of destruction of dependent singletons. At the program’s exit if a singleton destructor makes use of an already destroyed singleton, an undefined behavior occurs (most probably a segfault).</p>
<p>Andrei presents a couple of patterns that overcome this problem. The first one is the phoenix singleton, a special implementation supposed to re-build the instance on demand at the memory address it had before the destruction. The second one is the singleton with longevity, a design which provides a mechanism to control the order of the singleton destructions (by means of a priority queue).</p>
<p>As final aim all the patterns described in the book are blended into a unique, policy-based singleton: the SingletonHolder. The pattern presented is portable and allows the mix of different features, providing the user with a practical way to express her needs in a single definition.</p>
<p>This is the end of the story, period. But you have an overwhelming wish to undergo with a vivid hallucination, take a breath.</p>
<p>Let’s go about things in an orderly way.</p>
<p>First, the Meyers Singleton is dissected to proof it is a robust pattern if compiled with the GNU g++-4.x. Second, a list of attractive requirements for a perfect singleton is provided. Then, a novel, generic singleton implementation is presented.</p>
<p>Okay, I have to admit it. I have loved the Meyers singleton since the first time I studied it (love at first sight?). Meyers presents a very practical way to carry out a singleton class:</p>
<p><pre class="brush: cpp; gutter: false;">
class single
{
    public:
    static single &amp;
    instance()
    {
        static single one;
        return one;
    }

    private:
        single()
        {}
        ~single()
        {}

        single(const single &amp;);
        single &amp;operator=(const single&amp; );
};
</pre></p>
<p>The properties of the Meyers singleton are listed below: </p>
<ol>
<li>The class is not instantiable because both default constructor and destructor are private.</li>
<li>The class is not copy-constructible, nor assignable because both copy constructor and assingment operator are private and not implemented.</li>
<li>It is only possible to get a reference to a single instance (one) by means of the static method instance();</li>
<p>The instance is constructed on demand (the first time the instance method is called) and destructed at the program’s exit, in the reverse relative order of which other static objects (and potentially other singletons) are constructed.</ol>
<p><pre class="brush: cpp; gutter: false;">
single &amp;ref = single::instance();
</pre></p>
<p>This class looks great and indeed it is. But what exactly were the reasons that made Andrei to abandon this implementation?</p>
<p>Basically Andrei left it out because it does not provide a means to control  the order destruction. In my experience the dead reference problem is a minor problem because it is not common and shows up only when a singleton depends on another singletons during its descruction.</p>
<p>In my opinion what really matters is instead whether a singleton is supposed to be destructed or not at the program’s exit.</p>
<p>If the singleton is not, then the Meyers&#8217; implementation needs a minor change in the static member: The instance is allocated in the <a href="http://en.wikipedia.org/wiki/Memory_allocation">heap</a> by means of the new operator and it will not be automatically destroyed at the program&#8217;s exit.</p>
<p><pre class="brush: cpp; gutter: false;">
static single &amp;
instance()
{
    static single * one = new one;
    return *one;
}
</pre></p>
<p>On the other hand, if the singleton is supposed to be destroyed at the program exit and it depends on other singletons that must be destroyed as well, it is possible to control the order of the destructors by accessing their instances at the beginning of the program in the right reverse order:</p>
<p><pre class="brush: cpp; gutter: false;">
single_2::instance();
single_1::instance();
</pre></p>
<p>This is sufficient to fix the dead reference problem, which seems to be a minor problem that, all in all, it&#8217;s not worth striving for.</p>
<p>The second issue to cope with is the race condition which affects the constructor at the first invocation. Even if the standard does not guarantees anything about this issue, starting from the g++ 4 the initialization of function-scope static variables is thread-safe by default. This means that a singleton pattern that relies on local static variables is automagically made thread safe because the constructor is atomic.</p>
<p>The following snippet proves this concept:</p>
<p><pre class="brush: cpp; gutter: false;">
struct poc
{
     poc()
     {
         std::cout &lt;&lt; &quot;building...&quot;; std::cout.flush(); sleep(5);
         std::cout &lt;&lt; &quot;done\n&quot;;
     }

     ~poc()
     {
         std::cout &lt;&lt; __PRETTY_FUNCTION__ &lt;&lt; std::endl;
     }

     static poc &amp;
     instance()
     {
         static poc one;
         return one;
     }
};

void * thread(void *)
{
     poc &amp;r = poc::instance();
}

int main(int argc, char *argv[])
{
     ...
     pthread_create(&amp;thread_1, NULL, thread, NULL);
     pthread_create(&amp;thread_2, NULL, thread, NULL);
     ...
}

</pre></p>
<p>here’s the disassembled code of the static function poc::instance():</p>
<pre>(gdb) disassemble 'poc::instance()'
Dump of assembler code for function _ZN3poc8instanceEv:

0x0000000000400cb2 &lt;_ZN3poc8instanceEv+0&gt;:      push   %rbp
0x0000000000400cb3 &lt;_ZN3poc8instanceEv+1&gt;:      mov    %rsp,%rbp
0x0000000000400cb6 &lt;_ZN3poc8instanceEv+4&gt;:      sub    $0x30,%rsp
0x0000000000400cba &lt;_ZN3poc8instanceEv+8&gt;:      mov    $0x601428,%eax
0x0000000000400cbf &lt;_ZN3poc8instanceEv+13&gt;:     movzbl (%rax),%eax
0x0000000000400cc2 &lt;_ZN3poc8instanceEv+16&gt;:     test   %al,%al
0x0000000000400cc4 &lt;_ZN3poc8instanceEv+18&gt;:     jne    0x400d4f &lt;_ZN3poc8instanceEv+157&gt;
0x0000000000400cca &lt;_ZN3poc8instanceEv+24&gt;:     mov    $0x601428,%edi
0x0000000000400ccf &lt;_ZN3poc8instanceEv+29&gt;:     callq  0x400988 &lt;__cxa_guard_acquire@plt&gt;
0x0000000000400cd4 &lt;_ZN3poc8instanceEv+34&gt;:     test   %eax,%eax
0x0000000000400cd6 &lt;_ZN3poc8instanceEv+36&gt;:     setne  %al
0x0000000000400cd9 &lt;_ZN3poc8instanceEv+39&gt;:     test   %al,%al
0x0000000000400cdb &lt;_ZN3poc8instanceEv+41&gt;:     je     0x400d4f &lt;_ZN3poc8instanceEv+157&gt;
0x0000000000400cdd &lt;_ZN3poc8instanceEv+43&gt;:     movb   $0x0,-0x11(%rbp)
0x0000000000400ce1 &lt;_ZN3poc8instanceEv+47&gt;:     mov    $0x601430,%edi
0x0000000000400ce6 &lt;_ZN3poc8instanceEv+52&gt;:     callq  0x400c72
0x0000000000400ceb &lt;_ZN3poc8instanceEv+57&gt;:     movb   $0x1,-0x11(%rbp)
0x0000000000400cef &lt;_ZN3poc8instanceEv+61&gt;:     mov    $0x601428,%edi
0x0000000000400cf4 &lt;_ZN3poc8instanceEv+66&gt;:     callq  0x4009f8 &lt;__cxa_guard_release@plt&gt;
0x0000000000400cf9 &lt;_ZN3poc8instanceEv+71&gt;:     mov    $0x400c48,%edi
0x0000000000400cfe &lt;_ZN3poc8instanceEv+76&gt;:     mov    $0x6012e8,%edx
0x0000000000400d03 &lt;_ZN3poc8instanceEv+81&gt;:     mov    $0x601430,%esi
0x0000000000400d08 &lt;_ZN3poc8instanceEv+86&gt;:     callq  0x4009b8 &lt;__cxa_atexit@plt&gt;
0x0000000000400d0d &lt;_ZN3poc8instanceEv+91&gt;:     jmp    0x400d4f &lt;_ZN3poc8instanceEv+157&gt;
0x0000000000400d0f &lt;_ZN3poc8instanceEv+93&gt;:     mov    %rax,-0x28(%rbp)
0x0000000000400d13 &lt;_ZN3poc8instanceEv+97&gt;:     mov    %rdx,-0x20(%rbp)
0x0000000000400d17 &lt;_ZN3poc8instanceEv+101&gt;:    mov    -0x20(%rbp),%eax
...</pre>
<p>The calls __cxa_guard_acquire/__cxa_guard_release are injected by the compiler to make the spell: the construction of static variables/objects is atomic. Yet, the __cxa_atexit function is used to register the destructor for the static object called at the program’s exit (note that it’s also possible to prevent the guard injection by passing the option -fno-threadsafe-statics to g++ at compile time).</p>
<p>Cool. G++ makes the Meyers Singleton robust and thread-safe. It seems to be a perfect candidate for the our singleton, but some features are still missing. Here’s the wish-list:</p>
<ul>
<li>You’d like a generic singleton implemented by means of  <a href="http://en.wikipedia.org/wiki/Curiously_Recurring_Template_Pattern">CRTP pattern</a>:</li>
</ul>
<p><pre class="brush: cpp; gutter: false;">
class single: public more::singleton&lt;single, ... &gt;
{
</pre></p>
<ul>
<li> You’d like a generic singleton that enables various flavors: destructible (at the application’s exit) or indestructible:</li>
</ul>
<p><pre class="brush: cpp; gutter: false;">
class single : public more::singleton&lt;single, more::singleton_type, ...&gt;
{
    // or

class single : public more::singleton&lt;single, more::indestructible_singleton_type, ...&gt;
{

</pre></p>
<ul>
<li>You’d like a generic singleton that allows to CV-qualify the instance:</li>
</ul>
<p><pre class="brush: cpp; gutter: false;">
class single : public more::singleton&lt;single, const more::singleton_type, ... &gt;  // both cv qualifiers should be enabled
{
</pre></p>
<ul>
<li>You’d like a generic singleton that once a class publicly derives from it:</li>
</ul>
<ol>
<li>It is not instantiable (*).</li>
<li>It is not copyable, nor copy-constructible.</li>
<li>It inherits the static method instance() returning the CV-qualified reference (simple, const or volatile) of the instance created at the first access.</li>
</ol>
<ul>
<li>You’d like a generic singleton that allows a non-default constructible class to be a singleton.</li>
</ul>
<p style="padding-left:30px;">The parameters passed to the constructor will make sense only at the first access, and they should be ignored in the subsequent calls. Also it would be nice if it was possible to specify the types of the constructor parameters by means of a <a href="http://code.google.com/p/nicola-bonelli-repo/source/browse/trunk/codes%2B%2B/typelist.hh">TYPELIST</a>:</p>
<p><pre class="brush: cpp; gutter: false;">
class single : public more::singleton&lt;single, more::singleton_type, TYPELIST(int)&gt;
 {
    ...
    single(int value)
    : _M_member(value)
    {}
    ....
</pre></p>
<p>and somewhere in the code:</p>
<p><pre class="brush: cpp; gutter: false;">
single &amp; ref = single::instance(10); // build the instance passing 10
single &amp; ref = single::instance();   // access the instance and take a reference
</pre></p>
<p>Such a singleton implementation is available <a href="http://code.google.com/p/nicola-bonelli-repo/source/browse/trunk/codes.cpp/singleton.hh">here</a>, and except for the feature marked with (*) possible only with a minor trade-off, its design consists in a mixture of template meta-programming and TR1 type traits.</p>
<p>Just few notes about the necessary trade-off. Since is not possible to obtain a class deriving from a generic base that inherits a static member function supposed to build an instance of it (while the class itself is not to be instantiable), the only way to fulfill this requirement is to add to the class constructor an additional parameter defined private in the base class and only accessible from the static member.</p>
<p>Such additional parameter (<strong>base_type::tag</strong>) must be passed to the constructor as first argument:</p>
<p><pre class="brush: cpp; gutter: false;">
class single : public more::singletonTYPELIST(std::string, int)&gt;
{
    single(base_type::tag, const std::string &amp;s, int n)
    {}
};
</pre></p>
<p>That&#8217;s all folks. If you are far-seeing you can play with my <a href="http://code.google.com/p/nicola-bonelli-repo/source/browse/trunk/codes.cpp/singleton.hh">Singl﻿eton</a> and then use it in your projects, but don&#8217;t forget to buy me a beer in return.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nicolabonelli.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nicolabonelli.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nicolabonelli.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nicolabonelli.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nicolabonelli.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nicolabonelli.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nicolabonelli.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nicolabonelli.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nicolabonelli.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nicolabonelli.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nicolabonelli.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nicolabonelli.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nicolabonelli.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nicolabonelli.wordpress.com/39/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nicolabonelli.wordpress.com&amp;blog=17508&amp;post=39&amp;subd=nicolabonelli&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nicolabonelli.wordpress.com/2009/06/04/singleton-a-mirage-of-perfection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5befef1a4026910d0fd53c2dcf63bf6d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">nicolabonelli</media:title>
		</media:content>
	</item>
		<item>
		<title>All the things you have always wanted to know about writing a generic perfect forwarder</title>
		<link>http://nicolabonelli.wordpress.com/2009/06/02/all-the-things-you-have-always-wanted-to-know-about-writing-a-generic-perfect-forwarder/</link>
		<comments>http://nicolabonelli.wordpress.com/2009/06/02/all-the-things-you-have-always-wanted-to-know-about-writing-a-generic-perfect-forwarder/#comments</comments>
		<pubDate>Tue, 02 Jun 2009 09:11:06 +0000</pubDate>
		<dc:creator>Nicola</dc:creator>
				<category><![CDATA[c++]]></category>
		<category><![CDATA[C++0x]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[c++0x]]></category>
		<category><![CDATA[c/c++]]></category>

		<guid isPermaLink="false">http://nicolabonelli.wordpress.com/?p=9</guid>
		<description><![CDATA[A generic forwarder is a template function supposed to forward the passed arguments to a target function or a callable object (provided for example as an extra argument). To be perfect a forwarder must be able to be deployed in different contexts, allowing to pass both lvalue and rvalue parameters, yet having the template parameter [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nicolabonelli.wordpress.com&amp;blog=17508&amp;post=9&amp;subd=nicolabonelli&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>A generic forwarder is a template function supposed to forward the passed arguments to a target function or a callable object (provided for example as an extra argument).</p>
<p>To be perfect a forwarder must be able to be deployed in different contexts, allowing to pass both lvalue and rvalue parameters, yet having the template parameter types correctly deducted and the target function properly chosen from a possible overloaded set.</p>
<p>The current C++ standard does not allow to implement such a perfect forwarder that instead is enabled by means of C++0x <a href="http://www.artima.com/cppsource/rvalue.html">rvalue reference</a>. Nevertheless, a generic non-perfect but correct forwarded is possible with the help of <a href="http://awgn.antifork.org/tr1/reference-wrapper">tr1::reference_wrapper</a>.</p>
<p><span id="more-9"></span></p>
<p>The most desirable feature for a generic wrapper is a mechanism for passing the arguments to a target function that accepts them in different ways: by copy, by reference and by const reference.</p>
<p>The client of the generic forwarder, indeed, must be able to pass either lvalue or rvalue arguments in accordance with the target&#8217;s signature: that is if a target parameter (the parameter of the target function) is taken by non-const reference, the corresponding parameter passed to the wrapper should be provided accordingly (as lvalue).</p>
<p>In this study a comparison of three different forwarders is presented, introducing the concept of perfect forwarding enabled by means of rvalue references.</p>
<p>The following  function has been chosen as target object (it could be a functor or any other callable object):</p>
<p><pre class="brush: cpp; gutter: false;">
int fun(arg a1, const arg &amp;a2, arg &amp;a3)
{
    a3 = arg(1);
    ...
    return 0;
}
</pre></p>
<p>The first signature examined is the following one:</p>
<p><pre class="brush: cpp; gutter: false;">
template &lt;typename F, typename T1, typename T2, typename T3&gt;
int candidate_forwarder_1(F &amp;f, T1 &amp;t1, T2 &amp;t2, T3 &amp;t3)
{
    return fun(t1,t2,t3);
}
</pre></p>
<p>All the arguments are passed by non-const reference.</p>
<p>The candidate_forwarder_1 sports no performance loss in that no additional copy constructors are called during the parameters passing (comparisons are provided by <a href="http://code.google.com/p/nicola-bonelli-repo/source/browse/trunk/codes%2B%2B/the-perfect-forwarder.cc">test</a> #0 and #1). However such a wrapper has a flaw: The caller of this wrapper is not allowed to pass a temporary object although the target function was designed to accept it by value or by const reference (ie: the second parameter of function fun).</p>
<p>This weakness is a consequence of a rule imposed by the standard that does not allow a non-const reference to bind an rvalue. The rule is intended to prevent the modification of an rvalue (temporary object) that, prior to the understanding of the importance of the <em>move</em> and <em>forward semantic</em> of C++0x, did not make much sense.</p>
<p>To get out of this scrape a second candidate for the perfect forwarder is considered:</p>
<p><pre class="brush: cpp; gutter: false;">
template &lt;typename F, typename T1, typename T2, typename T3&gt;
int candidate_forwarder_2(F f, T1 t1, T2 t2, T3 t3)
{
    return fun(t1,t2,t3);
}
</pre></p>
<p>In this wrapper all the arguments are passed by value, which means that it&#8217;s possible to pass both lvalue and rvalue. However there&#8217;s a double problem here: not only are the arguments copy-constructed, but also the type deduction decay now comes into play. The decay makes array and function types resolved as pointers, as well as the top-level CV qualifiers discarded (see template argument deduction decay:  C++ Template: the complete guide [Vandevoorde/Josuttis]).</p>
<p>As a consequence this second candidate shows following problems:</p>
<ol>
<li> it&#8217;s not  perfect due to the template argument deduction decay. The template argument types may be resolved as types that cannot be used to select the proper target function (overloading failure).</li>
<li>parameters of the target function taken by reference are bound to the formal parameters of the forwarder (t3, in the example) and not to those provided by the forwarder client.</li>
<li>parameters are passed by value and additional copy constructors are involved.</li>
</ol>
<p>The <a href="http://code.google.com/p/nicola-bonelli-repo/source/browse/trunk/codes%2B%2B/the-perfect-forwarder.cc">test</a> #2 shows that the issue 2 makes this wrapper incorrect:</p>
<div style="margin-left:40px;"><em>the actual argument a3 passed to the wrapper is not updated by the target function as expected (the formal parameter t3 is updated in place of it).</em></div>
<p>Fortunately a workaround exists: the tr1::reference_wrapper class can be used to wrap the arguments supposed to be passed as non-const reference to the target function.</p>
<p>Hence if the instantiation point is like just this one:</p>
<p><pre class="brush: cpp; gutter: false;">
candidate_forwarder_2(fun, a1, a2, std::tr1::ref(a3));
</pre></p>
<p>the wrapper produces the expected result.<a href="http://code.google.com/p/nicola-bonelli-repo/source/browse/trunk/codes%2B%2B/the-perfect-forwarder.cc"> Test</a> #3 and #4 show the correctness of the forwarder function.</p>
<p>Alas the comparison of the <a href="http://code.google.com/p/nicola-bonelli-repo/source/browse/trunk/codes%2B%2B/the-perfect-forwarder.cc">test</a> #0 and #4 shows further copy constructors involved when passing the argument a1 and a2 (*3). This is the price to pay to implement a wrapper that can accept both lvalue and rvalue parameters.</p>
<p>It&#8217;s worth noting that when passing an rvalue object no additional copy constructor is involved thanks to the copy elision optimization implemented in most of the compilers available today. The <a href="http://code.google.com/p/nicola-bonelli-repo/source/browse/trunk/codes%2B%2B/the-perfect-forwarder.cc">test</a> #3 shows such an optimization in action:</p>
<p><pre class="brush: cpp; gutter: false;">
candidate_forwarder_2(fun, arg(), arg(), std::tr1::ref(a3));
</pre></p>
<p>In despite of the sub optimal performance pointed out by the <a href="http://code.google.com/p/nicola-bonelli-repo/source/browse/trunk/codes%2B%2B/the-perfect-forwarder.cc">test</a> #4, the candidate_forwarder_2 wrapper is however preferable over the candidate_forwarder_1, in that it admits rvalues and temporaries as arguments.</p>
<p>Although not perfect (*1), it&#8217;s the most convenient implementation the current C++ standard allows to implement. The object adapter <a href="http://awgn.antifork.org/tr1/bind">tr1::bind</a>, for instance, is written exactly this way.</p>
<p>As final candidate, the perfect forwarder is presented. It is implemented by means of C++0x rvalue reference:</p>
<p><pre class="brush: cpp; gutter: false;">
template &lt;typename F, typename T1, typename T2, typename T3&gt;
int the_perfect_forwarder(F f, T1 &amp;&amp;t1, T2 &amp;&amp;t2, T3 &amp;&amp;t3)
{
    return fun(std::forward&lt;T1&gt;(t1),
               std::forward&lt;T2&gt;(t2),
               std::forward&lt;T3&gt;(t3));
}
</pre></p>
<p>The limitation that a non-const reference cannot bind an rvalue is removed by means of the rvalue reference [&amp;&amp;] which is supposed to bind to both lvalues and rvalues when it&#8217;s a template parameter.<br />
Bearing in mind the  <a rel="nofollow" href="http://thbecker.net/articles/rvalue_references/section_07.html">reference collapsing rules</a> introduced by C++0x :</p>
<ul>
<li>T&amp;  -&gt; &amp;  -&gt; T&amp;</li>
</ul>
<ul>
<li>T&amp;  -&gt; &amp;&amp; -&gt; T&amp;</li>
</ul>
<ul>
<li>T&amp;&amp; -&gt; &amp;  -&gt; T&amp;</li>
</ul>
<ul>
<li>T&amp;&amp; -&gt; &amp;&amp; -&gt; T&amp;&amp;</li>
</ul>
<p>The last forwarder sports the following properties:</p>
<ul>
<li>No additional copy constructors are involved during the argument passing.</li>
</ul>
<ul>
<li>Either a lvalue or an rvalue can be provided as argument, in accordance with the signature of the target function/object.</li>
</ul>
<ul>
<li>The template argument deduction for an rvalue reference is done in the following way:
<ul>
<li>if a lvalue of type A is passed, T resolves to A&amp; and by the reference collapsing rules, the argument type becomes A&amp; (lvalue reference);</li>
<li>if an rvalue is passed, T resolves to A, and the argument type becomes A&amp;&amp; (no collapsing rule is applied).</li>
</ul>
</li>
</ul>
<p>However the rvalue reference itself is not sufficient to implement a perfect forwarder because once the arguments are passed to the wrapper they have a name and therefore they all are l-values. To restore their original type the std::forward&lt;&gt; helper function can be used to implement the correct forward semantic:</p>
<p><pre class="brush: cpp; gutter: false;">
namespace std
{
    template &lt;typename T&gt;
    &amp;&amp; forward(T&amp;&amp; a)
    {
        return a;
    }
}
</pre></p>
<p>Why std::forward&lt;&gt; is required? Let&#8217;s do an in-depth examination:</p>
<ul>
<li>If a lvalue of type A is passed to <strong>std::forward</strong><strong>&lt;&gt;</strong> as argument, the corresponding type T of the wrapper resolves to A&amp;. Then by the collapsing rules, the argument and the return type of std::forward become A&amp;.</li>
</ul>
<ul>
<li> If a rvalue of type A is passed to <strong>std::forward&lt;&gt;</strong><strong> </strong>as argument, the corresponding type T of the wrapper resolves to A. Then the argument and the return type of std::forward become A&amp;&amp;.</li>
</ul>
<p>That said, the return type of std::forward&lt;&gt; depends on type explicitly specified in the template at the instantiation point (argument deduction is not used in the std::forward). If it&#8217;s not yet clear, the following rule puts more light on the problem:</p>
<blockquote><p>Objects declared as rvalue reference can be either lvalues or rvalues. The distinguishing criterion to bear in mind is: if the instance has a name then it is a lvalue; an rvalue otherwise.</p></blockquote>
<p>In accordance with this criterion it follows that:</p>
<blockquote><p>The return type of std::forward is an expression that (since it has no-name) it is an rvalue reference when an rvalue object is passed as argument, or a lvalue reference otherwise.</p></blockquote>
<p>The std::forward template function used in the perfect forwarder returns an expression whose type is exactly the same as that of the argument passed to the wrapper. This enables the perfect forwarding.</p>
<p>Ciao</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nicolabonelli.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nicolabonelli.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nicolabonelli.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nicolabonelli.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nicolabonelli.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nicolabonelli.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nicolabonelli.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nicolabonelli.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nicolabonelli.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nicolabonelli.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nicolabonelli.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nicolabonelli.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nicolabonelli.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nicolabonelli.wordpress.com/9/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nicolabonelli.wordpress.com&amp;blog=17508&amp;post=9&amp;subd=nicolabonelli&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nicolabonelli.wordpress.com/2009/06/02/all-the-things-you-have-always-wanted-to-know-about-writing-a-generic-perfect-forwarder/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5befef1a4026910d0fd53c2dcf63bf6d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">nicolabonelli</media:title>
		</media:content>
	</item>
		<item>
		<title>Hello world!</title>
		<link>http://nicolabonelli.wordpress.com/2006/06/27/hello-world/</link>
		<comments>http://nicolabonelli.wordpress.com/2006/06/27/hello-world/#comments</comments>
		<pubDate>Tue, 27 Jun 2006 08:05:16 +0000</pubDate>
		<dc:creator>Nicola</dc:creator>
				<category><![CDATA[networking]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://nicolabonelli.wordpress.com/?p=3</guid>
		<description><![CDATA[Hello World. My name is Nicola. I&#8217;m a determined hacker, a unix hacker by choice and attitude. I have been an enthusiastic linux programmer since 1995. I have developed opensource applications using i386 AT&#38;T assembler, GNU C and recently C++ languages solely for fun. I believe in the opensource philosophy, I am debian addicted and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nicolabonelli.wordpress.com&amp;blog=17508&amp;post=3&amp;subd=nicolabonelli&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Hello World.</p>
<p>My name is Nicola. I&#8217;m a determined <a href="http://www.catb.org/jargon/html/H/hacker.html">hacker</a>, a unix hacker by choice and attitude. I have been an enthusiastic linux programmer since 1995. I have developed opensource applications using i386 AT&amp;T assembler, <a href="http://www.gnu.org/">GNU</a> C and recently C++ languages solely for fun. I believe in the <a href="http://www.opensource.org/">opensource</a> philosophy, I am <a href="http://www.debian.org/">debian</a> addicted and more importantly I love <a href="http://www.snowboarding.com/">snowboarding</a>.</p>
<p><span id="more-3"></span></p>
<p>After the masters in telecommunication engineering I worked for some years at the department of <a href="http://www.ing.unipi.it/">Information Engineering of the University of Pisa</a> (Italy) as <a href="http://wwwtlc.iet.unipi.it/">research assistant</a>. My research activity focused the performance evaluation and optimization of device drivers of network adapters.</p>
<p>During that time I developed <a href="http://code.google.com/p/brute/">brute</a>, actually the fastest and the most reliable traffic generator available for the linux operating system. Brute outclasses paired software in terms of performance and accuracy, providing users with a set of API that eases the development and enables the customization of generic traffic models. Brute was presented at SPECT05, an international <a href="http://www.scs.org/">SCS</a> conference held in Philadelphia.</p>
<p>Another research project I worked on is a linux LKM intended to handle classifiers and schedulers at link layer of the 802.11 wireless protocol. L2FW, the name of the framework, is built on the top of the <a href="http://hostap.epitest.fi/">HostAP</a> driver with the aim to improve the performance of Prims2 adapters when running as AP. On the top of L2FW with the guidance of Rosario Garroppo and Stefano Lucetti I then developed a channel-aware scheduler that, in conjunction with a mac classifier, avoids the performance anomaly of 802.11[bg] wireless networks.</p>
<p>Among other projects, it&#8217;s worth mentioning a linux interrupt-handler hack (do_IRQ) &#8212; a work I sketched with my colleague Francesco Oppedisano. The hack  aims at implementing a refurbished version of <a href="http://www.tldp.org/HOWTO/Ethernet-HOWTO.html">NAPI</a> that we could name New NAPI (NNAPI).  NNAPI aims to fill the gap left about the capability to timestamp packets in gigabit ethernet device drivers (tests were conducted with intel epro1000 ethernet adapter). From the traffic characterization point of view, in fact, the accuracy of NAPI timestamping  is not adequate and needs to be improved.  NNAPI enhances the  accuracy of timestamps by three order of magnitude &#8212; cloned timestamps pass from some thousand to a few.</p>
<p>A uber-lightweight interrupt handler that sports a minor latency reduced roughly to that of the interrupt PIC replaces the interrupt mitigation scheme. Unfortunately, quite predictable, the high precision of timestamping is achived to a detriment of performance in terms of packets captured per second. The project needs to be refined a bit. Hopefully the NNAPI source code will be released someday.</p>
<p>At the present moment I am employed at a company operating in the information and communication technology sector. I left the academic world last January.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/nicolabonelli.wordpress.com/3/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/nicolabonelli.wordpress.com/3/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nicolabonelli.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nicolabonelli.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nicolabonelli.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nicolabonelli.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nicolabonelli.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nicolabonelli.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nicolabonelli.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nicolabonelli.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nicolabonelli.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nicolabonelli.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nicolabonelli.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nicolabonelli.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nicolabonelli.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nicolabonelli.wordpress.com/3/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nicolabonelli.wordpress.com&amp;blog=17508&amp;post=3&amp;subd=nicolabonelli&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nicolabonelli.wordpress.com/2006/06/27/hello-world/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5befef1a4026910d0fd53c2dcf63bf6d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">nicolabonelli</media:title>
		</media:content>
	</item>
	</channel>
</rss>
