<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/atom10full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" gd:etag="W/&quot;DEYHR344eCp7ImA9WhVbEE4.&quot;"><id>tag:blogger.com,1999:blog-13960885</id><updated>2012-05-26T06:42:16.030-06:00</updated><category term="meta-programming constexpr performance" /><category term="traits compile-time algorithm selection templates" /><category term="policy clone idiom &quot;policy-based class design&quot;" /><category term="&quot;Counted Method Chaining&quot; &quot;Template Meta-programming&quot;" /><title type="text">C++ Truths</title><subtitle type="html">A C++ blog on intermediate to advanced topics in C++ programming language features, standards, idioms, design patterns, and object-oriented programming in general.</subtitle><link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://cpptruths.blogspot.com/feeds/posts/default" /><link rel="alternate" type="text/html" href="http://cpptruths.blogspot.com/" /><link rel="next" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default?start-index=26&amp;max-results=25&amp;redirect=false&amp;v=2" /><author><name>Sumant</name><uri>http://www.blogger.com/profile/11957855386259543653</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="28" height="32" src="http://4.bp.blogspot.com/--0WncXMeBPA/TchxRepk7bI/AAAAAAAABXo/oLNnYnw0K7A/s1600/Sumant-Tambe.JPG" /></author><generator version="7.00" uri="http://www.blogger.com">Blogger</generator><openSearch:totalResults>85</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/atom+xml" href="http://feeds.feedburner.com/CppTruths" /><feedburner:info uri="cpptruths" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><logo>http://www.dre.vanderbilt.edu/~sutambe/images/cpp_small.jpg</logo><entry gd:etag="W/&quot;DEcER3o8eCp7ImA9WhVSFks.&quot;"><id>tag:blogger.com,1999:blog-13960885.post-761579936053967259</id><published>2012-03-09T01:18:00.015-07:00</published><updated>2012-03-13T13:13:26.470-06:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-03-13T13:13:26.470-06:00</app:edited><title>Rvalue references in constructor: when less is more</title><content type="html">I've seen a recurring mistake made by well-versed C++03 programmers when they set out to use rvalue references for the first time. In fact, as it turns out, better you are at C++03, easier it is to fall in the trap of rvalue reference anti-pattern I'm gonna talk about.&lt;br /&gt;&lt;br /&gt;Consider the following C++03 class:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;&lt;br /&gt;class Book {&lt;br /&gt;public:&lt;br /&gt;  Book(const std::string &amp; title,&lt;br /&gt;       const std::vector&amp;lt;std::string&amp;gt; &amp; authors,&lt;br /&gt;       const std::string &amp; pub,&lt;br /&gt;       const size_t &amp; pub_day&lt;br /&gt;       const std::string &amp; pub_month,&lt;br /&gt;       const size_t &amp; pub_year)&lt;br /&gt;    : _title(title),&lt;br /&gt;      _authors(authors),&lt;br /&gt;      _publisher(pub),&lt;br /&gt;      _pub_day(pub_day),&lt;br /&gt;      _pub_month(pub_month),&lt;br /&gt;      _pub_year(pub_year)&lt;br /&gt;     {}&lt;br /&gt;&lt;br /&gt;     // ....&lt;br /&gt;     // ....&lt;br /&gt;&lt;br /&gt;private:&lt;br /&gt;  std::string _title;&lt;br /&gt;  std::vector&amp;lt;std::string&amp;gt; _authors;&lt;br /&gt;  std::string _publisher;&lt;br /&gt;  size_t      _pub_day;&lt;br /&gt;  std::string _pub_month;&lt;br /&gt;  size_t      _pub_year;&lt;br /&gt;};&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The &lt;span style="font-style:italic;"&gt;Book&lt;/span&gt; class above is as dull as it can be. Now lets C++11'fy it! C++11 gives us shiny new rvalue references and &lt;span style="font-style:italic;"&gt;std::move&lt;/span&gt;. So lets add them.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;&lt;br /&gt;class Book {&lt;br /&gt;public:&lt;br /&gt;  Book(const std::string &amp; title,&lt;br /&gt;       const std::vector&amp;lt;std::string&amp;gt; &amp; authors,&lt;br /&gt;       const size_t      &amp; pub_day&lt;br /&gt;       const std::string &amp; pub_month,&lt;br /&gt;       const size_t      &amp; pub_year)&lt;br /&gt;    : _title    (title),&lt;br /&gt;      _author   (author),&lt;br /&gt;      _pub_day  (pub_day),&lt;br /&gt;      _pub_month(pub_month),&lt;br /&gt;      _pub_year (pub_year)&lt;br /&gt;     {}&lt;br /&gt;&lt;br /&gt;  Book(std::string &amp;&amp; title,&lt;br /&gt;       std::vector&amp;lt;std::string&amp;gt; &amp;&amp; authors,&lt;br /&gt;       size_t      &amp;&amp; pub_day&lt;br /&gt;       std::string &amp;&amp; pub_month,&lt;br /&gt;       size_t      &amp;&amp; pub_year)&lt;br /&gt;    : _title    (std::move(title)),&lt;br /&gt;      _authors  (std::move(authors)),&lt;br /&gt;      _pub_day  (pub_day),&lt;br /&gt;      _pub_month(std::move(pub_month)),&lt;br /&gt;      _pub_year (pub_year)&lt;br /&gt;     {}&lt;br /&gt;&lt;br /&gt;     // ....&lt;br /&gt;     // ....&lt;br /&gt;&lt;br /&gt;private:&lt;br /&gt;  std::string _title;&lt;br /&gt;  std::vector&amp;lt;std::string&amp;gt; _authors;&lt;br /&gt;  size_t      _pub_day;&lt;br /&gt;  std::string _pub_month;&lt;br /&gt;  size_t      _pub_year;&lt;br /&gt;};&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Is our constructor optimally move-enabled? It's far from it! More often that not, programmers' legit code will end up calling the old constructor instead of the the new one, which probably means lost opportunities for optimization. It could be hard to see what's wrong in the new class to an untrained eye. We've test it to see what's really wrong with it.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;&lt;br /&gt;std::string &amp; toUpper(std::string &amp; s)&lt;br /&gt;{&lt;br /&gt;  std::transform(s.begin(), s.end(), s.begin(), toupper);&lt;br /&gt;  return s;&lt;br /&gt;}&lt;br /&gt;const std::string &amp; January()&lt;br /&gt;{&lt;br /&gt;  static std::string jan("January");&lt;br /&gt;  return jan;&lt;br /&gt;}&lt;br /&gt;int main(void)&lt;br /&gt;{&lt;br /&gt;  std::vector&amp;lt;std::string&amp;gt; authors { "A", "B", "C" };&lt;br /&gt;  Book b1("Book1", authors, 1, "Jan", 2012);   // old c-tor&lt;br /&gt;&lt;br /&gt;  size_t year = 2012&lt;br /&gt;  Book b2("Book2", { "A", "B", "C" }, 1, "Jan", year); // old c-tor&lt;br /&gt;&lt;br /&gt;  std::string month = "Mar";&lt;br /&gt;  Book b3("Book3", { "Author" }, 1, toUpper(month), 2012); // old c-tor&lt;br /&gt;&lt;br /&gt;  Book b4("Book4", { "Author" }, 1, January(), 2012); // old c-tor&lt;br /&gt;&lt;br /&gt;  std::string book = "Book";&lt;br /&gt;  Book b5(std::move(book), std::move(authors), 1, std::move(month), year); // old-ctor&lt;br /&gt;&lt;br /&gt;  Book b6("Book", { "Author" }, 1, "Jan", 2012); // new c-tor!&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;It may come as a surprise that in all but one case above, the old constructor is called. Only in the last case, the new-ctor is called, which makes the minimum number of copies. So what's the gotcha?&lt;br /&gt;&lt;br /&gt;As it turns out, the &lt;span style="font-style:italic;"&gt;Book&lt;/span&gt; constructors are stopping the compiler from doing a better job. The first constructor takes &lt;span style="font-weight:bold;"&gt;all&lt;/span&gt; the parameters as const reference and the second one takes &lt;span style="font-weight:bold;"&gt;all&lt;/span&gt; the parameters as rvalue reference. Unless and until all the the parameters passed to the constructor are temporary objects (rvalues) or literals, the second constructor does not kick in. This implies lost optimization opportunities for parameters that &lt;span style="font-style:italic;"&gt;are&lt;/span&gt; temporary (so can be moved) but won't be moved because some other parameter botched the soup. These two constructors give you very limited options: all-or-nothing.&lt;br /&gt;&lt;br /&gt;In case of b1, &lt;span style="font-style:italic;"&gt;authors &lt;/span&gt;is an lvalue and it does not bind to an rvalue ref.&lt;br /&gt;In case of b2, &lt;span style="font-style:italic;"&gt;year &lt;/span&gt; is an lvalue and does not bind to an rvalue ref.&lt;br /&gt;In case of b3, &lt;span style="font-style:italic;"&gt;toUpper &lt;/span&gt;returns a string reference; Does no good.&lt;br /&gt;In case of b4, &lt;span style="font-style:italic;"&gt;January &lt;/span&gt;returns a const string reference; same story!&lt;br /&gt;In case of b5, &lt;span style="font-style:italic;"&gt;year &lt;/span&gt; is an lvalue that prevents calling the second constructor although programmer tries to explicitly move all the string and vector parameters. In reality, the actual moves do not happen and if the remaining program depends on the moves being successful may not be very happy.&lt;br /&gt;&lt;br /&gt;Only in case of b6, all actual parameters are rvalues or literals. Therefore, the "all-rvalue-ref" constructor is called. Note that temporary string objects will be implicitly created where string literals are used.&lt;br /&gt;&lt;br /&gt;So lets fix it. What we really need is just one constructor that accepts all the parameters by value. As a side-effect, the overall code is much simpler.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;&lt;br /&gt;class Book {&lt;br /&gt;public:&lt;br /&gt;  Book(std::string title,&lt;br /&gt;       std::vector&amp;lt;std::string&amp;gt; authors,&lt;br /&gt;       size_t      pub_day&lt;br /&gt;       std::string pub_month,&lt;br /&gt;       size_t      pub_year)&lt;br /&gt;    : _title    (std::move(title)),&lt;br /&gt;      _authors  (std::move(authors)),&lt;br /&gt;      _pub_day  (pub_day),&lt;br /&gt;      _pub_month(std::move(pub_month)),&lt;br /&gt;      _pub_year (pub_year)&lt;br /&gt;     {}&lt;br /&gt;&lt;br /&gt;  // ....&lt;br /&gt;  // ....&lt;br /&gt;};&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;That's it! This is our &lt;span style="font-style:italic;"&gt;the&lt;/span&gt; constructor that works optimally. All strings, vectors, integral types are passed by value. Within the constructor, the pass-by-value parameters that are on the stack-frame must be moved to the respective data members. The reason is that the lifetime of pass-by-value parameters is anyways limited to the lifetime of the constructor call itself. We want to tie their lifetime to the &lt;span style="font-style:italic;"&gt;object&lt;/span&gt; and not the constructor.&lt;br /&gt;&lt;br /&gt;This constructor does no more deep copies of than necessary. And that number really depends on how it is called. Due to pass-by-value semantics, each object &lt;span style="font-weight:bold;"&gt;individually&lt;/span&gt; is an opportunity for the compiler to perform a move when a temporary is involved. Lets revisit our b1 to b4 objects.&lt;br /&gt;&lt;br /&gt;In case of b1, except for &lt;span style="font-style:italic;"&gt;authors&lt;/span&gt; all other parameters are copied and moved once.&lt;br /&gt;In case of b2, all strings and vectors are copied and moved once. That's what matters.&lt;br /&gt;In case of b3, &lt;span style="font-style:italic;"&gt;toUpper &lt;/span&gt;returns an string reference; everything else copied and moved only once.&lt;br /&gt;In case of b4, &lt;span style="font-style:italic;"&gt;January &lt;/span&gt;returns a const string reference; everything else copied and moved once.&lt;br /&gt;In case of b5, strings are vector are moved as expected and in fact the b5 object the local parameters are created using move-constructor and moved again into the data member. Hence the object is created without any deep copies (like zero-copy).&lt;br /&gt;&lt;br /&gt;Using pass-by-value also opens other opportunities to eliminate temporaries when functions return by value and are used as actual parameters. However, I won't discuss that in detail here. &lt;br /&gt;&lt;br /&gt;Finally, I want to conclude saying that this whole thing assumes that a move is much cheaper than a deep-copy. This is generally true for std::vector and std::string where memory is allocated dynamically. For small strings however small-string-optimization may make copy and move practically equivalent.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/13960885-761579936053967259?l=cpptruths.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CppTruths/~4/Q5ebborUXj8" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://cpptruths.blogspot.com/feeds/761579936053967259/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=13960885&amp;postID=761579936053967259" title="22 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/761579936053967259?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/761579936053967259?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CppTruths/~3/Q5ebborUXj8/rvalue-references-in-constructor-when.html" title="Rvalue references in constructor: when less is more" /><author><name>Sumant</name><uri>http://www.blogger.com/profile/11957855386259543653</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="28" height="32" src="http://4.bp.blogspot.com/--0WncXMeBPA/TchxRepk7bI/AAAAAAAABXo/oLNnYnw0K7A/s1600/Sumant-Tambe.JPG" /></author><thr:total>22</thr:total><feedburner:origLink>http://cpptruths.blogspot.com/2012/03/rvalue-references-in-constructor-when.html</feedburner:origLink></entry><entry gd:etag="W/&quot;A0EGR3Y4eSp7ImA9WhRUE0U.&quot;"><id>tag:blogger.com,1999:blog-13960885.post-1512032382027272749</id><published>2012-01-22T12:31:00.012-07:00</published><updated>2012-01-24T00:20:26.831-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-01-24T00:20:26.831-07:00</app:edited><title>Array-like access and Iterators for Homogeneous Tuples</title><content type="html">Question often comes up whether tuples can have traditional iterators? In general, the answer is: No! They cannot. That's because tuples typically contain different types and traditional iterators, which are modeled after pointers, can not dereference to objects of multiple types. However, &lt;span style="font-style:italic;"&gt;homogeneous&lt;/span&gt; tuples can have iterators. So I thought it would be a fun exercise to write one. I wonder why one would use a homogeneous tuples instead of just plain arrays. But lets do it anyways because we can.&lt;br /&gt;&lt;br /&gt;Although this exercise sounds rather naive and unnecessary, I stumbled upon two very interesting topics along the way.&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;A need for &lt;a href="http://www.boost.org/libs/iterator/doc/new-iter-concepts.html"&gt;new iterator concepts&lt;/a&gt; to separate the notions of element access from iterator traversal. Yes! iterators for homogeneous tuples can't be modeled accurately using conventional iterator categories. Don't believe me? Please read on...&lt;/li&gt;&lt;br /&gt;&lt;li&gt;How inherited constructors may be simulated on compilers that don't support them today.&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;From this point onward a tuple is assumed to be a homogeneous tuple. First thing we need is a way of accessing tuple's contents using a run-time integer instead of a compile-time integer. We need an adapter that uses a run-time integer index to return the &lt;span style="font-style:italic;"&gt;n&lt;/span&gt;-th element in a homogeneous tuple. If n is larger than the bounds of the tuple, the adapter will throw a std::out_of_range exception.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;template &amp;lt;typename Tuple,&lt;br /&gt;        size_t I = std::tuple_size&amp;lt;Tuple&amp;gt;::value-1&amp;gt;&lt;br /&gt;class TupleAt&lt;br /&gt;{&lt;br /&gt;   typedef typename std::tuple_element&amp;lt;0, Tuple&amp;gt;::type T;&lt;br /&gt;&lt;br /&gt; public:&lt;br /&gt;   static T &amp;amp; get(Tuple &amp;amp; tuple, size_t index)&lt;br /&gt;   {&lt;br /&gt;     return (index == I)? std::get&amp;lt;I&amp;gt;(tuple) : TupleAt&amp;lt;Tuple, I-1&amp;gt;::get(tuple, index);&lt;br /&gt;   }&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;template &amp;lt;typename Tuple&amp;gt;&lt;br /&gt;class TupleAt&amp;lt;Tuple, 0&amp;gt;&lt;br /&gt;{&lt;br /&gt;   typedef typename std::tuple_element&amp;lt;0, Tuple&amp;gt;::type T;&lt;br /&gt; public:&lt;br /&gt;&lt;br /&gt;   static T &amp;amp; get(Tuple &amp;amp; tuple, size_t index)&lt;br /&gt;   {&lt;br /&gt;     if(index == 0)&lt;br /&gt;       return std::get&amp;lt;0&amp;gt;(tuple);&lt;br /&gt;     else&lt;br /&gt;       throw std::out_of_range("Tuple iterator dereferenced out of valid range.");&lt;br /&gt;   }&lt;br /&gt;};&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The &lt;span style="font-style:italic;"&gt;TupleAt&lt;/span&gt; template takes the type of the tuple and its size as template parameters. It assumes that the type of the first element is also the type of the rest of the elements in the tuple (i.e. a homogeneous tuple). &lt;span style="font-style:italic;"&gt;TupleAt::get&lt;/span&gt; function returns a reference to the &lt;span style="font-style:italic;"&gt;n&lt;/span&gt;-th element in the tuple. It does that using repeated comparisons from the size of the tuple (std::tuple_size&amp;lt;Tuple&amp;gt;::value) down to zero. TupleAt is specialized for zero so that the recursion ends. If the index does not fall in the expected range, std::out_of_range exception is thrown.&lt;br /&gt;&lt;br /&gt;Note that this access pattern is &lt;span style="font-style:italic;"&gt;linear&lt;/span&gt; in complexity. For a tuple of N elements, it may take up to N comparisons to return the right element.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Array-like access to Homogeneous Tuples&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;I created a &lt;span style="font-style:italic;"&gt;tuple_array&lt;/span&gt; class to provide array-like access to the elements of the tuple. It uses TupleAt internally.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;template &amp;lt;typename... T&amp;gt;&lt;br /&gt;class tuple_array : public std::tuple&amp;lt;T...&amp;gt;&lt;br /&gt;{&lt;br /&gt;   typedef std::tuple&amp;lt;T...&amp;gt; Tuple;&lt;br /&gt;   typedef typename std::tuple_element&amp;lt;0, Tuple&amp;gt;::type HeadType;&lt;br /&gt;   enum { TUPLE_SIZE = std::tuple_size&amp;lt;tuple&amp;gt;::value };&lt;br /&gt;&lt;br /&gt;   HeadType * ref_;&lt;br /&gt;   size_t last_;&lt;br /&gt;&lt;br /&gt; public:&lt;br /&gt;   USING(tuple_array, Tuple)&lt;br /&gt;   {&lt;br /&gt;     ref_ = &amp;amp; TupleAt&amp;lt;tuple&amp;gt;::get(*this, TUPLE_SIZE-1);&lt;br /&gt;     last_ = TUPLE_SIZE-1;&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   HeadType &amp;amp; operator [] (size_t index)&lt;br /&gt;   {&lt;br /&gt;     if(last_ != index)&lt;br /&gt;     {&lt;br /&gt;       ref_ = &amp;amp; TupleAt&amp;lt;tuple&amp;gt;::get(*this, index);&lt;br /&gt;       last_ = index;&lt;br /&gt;     }&lt;br /&gt;     return *ref_;&lt;br /&gt;   }&lt;br /&gt;};&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Class tuple_array inherits from std::tuple and just provides &lt;span style="font-style:italic;"&gt;operator []&lt;/span&gt; function. It always returns a reference to HeadType typedef, which is the type of the first element in the tuple. To improve efficiency, the tuple_array class caches a pointer to the last dereferenced index in the tuple. std::tuple has a zillion constructors to create a tuple. To avoid repeating the constructors in the derived tuple_array class, I wanted to use inherited constructors. However, g++ 4.7 does not support it at this moment. So I'm using a variadic template constructor to mimic the behavior of inherited constructors.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;#define USING(Dervied, Base)                                       \&lt;br /&gt;     template&amp;lt;typename ...Args,                                   \&lt;br /&gt;            typename = typename std::enable_if                    \&lt;br /&gt;            &amp;lt;                                                     \&lt;br /&gt;               std::is_constructible&amp;lt;Base, Args...&amp;gt;::value        \&lt;br /&gt;            &amp;gt;::type&amp;gt;                                              \&lt;br /&gt;   Dervied(Args &amp;amp;&amp;amp;...args)                                        \&lt;br /&gt;       : Base(std::forward&amp;lt;Args&amp;gt;(args)...)                        \&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The inherited constructor trick is captured in a macro, which I stole shamelessly from &lt;a href="http://stackoverflow.com/questions/5411229/c0x-inherited-constructor-in-templates/5411992#5411992"&gt;here&lt;/a&gt;. The USING macro defines a variadic template constructor and forwards all the arguments to the underlying base constructor. To avoid being overly greedy, it enables instantiation only if the base is &lt;span style="font-style:italic;"&gt;constructible&lt;/span&gt; from the given parameters. std::is_constructible&amp;lt;Base, Args...&amp;gt;::value provides a neat way of checking that at compile-time.&lt;br /&gt;&lt;br /&gt;Finally, we need a simple function to create the tuple_array. Function make_tuple_array is a factory function to create tuple_arrays from a list of arguments. Note how it uses the uniform initialization syntax without specifying the actual type. Using make_tuple_array is just like an array. However, note that element access is linear and not constant-time.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;template &amp;lt;typename... T&amp;gt;&lt;br /&gt;tuple_array&amp;lt;T...&amp;gt; make_tuple_array(T... args)&lt;br /&gt;{&lt;br /&gt; return { std::forward&amp;lt; T&amp;amp;&amp;amp; &amp;gt;(args)... };&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main(void)&lt;br /&gt;{&lt;br /&gt; auto ta = make_tuple_array(20, 30, 40);&lt;br /&gt; printf("%d %d %d", ta[0], ta[1], ta[2]); // prints 20 30 40&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Iterators for Homogeneous Tuples&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;Now lets turn our attention to iterators.&lt;br /&gt;&lt;br /&gt;What category would an iterator for homogeneous tuple belong? Random access? Bidirectional? It appears to me that the homogeneous tuple iterator could simply use an internal index to remember what position it is at and use the TupleAt::get to return the element when dereferenced. Arbitrary arithmetic can be performed in constant-time on the internal index to move the iterator. This indicates that the iterator is a random access iterator.&lt;br /&gt;&lt;br /&gt;However, the dereference function is not constant-time as discussed earlier. As a result, it is &lt;u&gt;&lt;span style="font-style:italic;"&gt;not&lt;/span&gt;&lt;/u&gt; a random access iterator. Clearly, traversal is random access but element access is not. Existing iterator categories do not support this distinction. The standard &lt;a href="http://www.sgi.com/tech/stl/RandomAccessIterator.html#5"&gt;random access iterator [5]&lt;/a&gt; requires all operations to be amortized constant time.&lt;br /&gt;&lt;br /&gt;What we really need is a way to distinguish between the categories of element access and the categories of traversal. This is precisely the point of &lt;a href="http://www.boost.org/libs/iterator/doc/new-iter-concepts.html"&gt;new iterator concepts &lt;/a&gt; in boost.&lt;br /&gt;&lt;br /&gt;For now, we'll just consider that the iterator for homogeneous tuple is a random access iterator. Here is how it looks like with a lot of boilerplate overloaded operators.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;template &amp;lt;typename Tuple&amp;gt;&lt;br /&gt;class tuple_iterator &lt;br /&gt;  : public std::iterator&amp;lt;std::random_access_iterator_tag,&lt;br /&gt;                         typename std::tuple_element&amp;lt;0, Tuple&amp;gt;::type&amp;gt;&lt;br /&gt;{&lt;br /&gt;   typedef typename std::tuple_element&amp;lt;0, Tuple&amp;gt;::type T;&lt;br /&gt;   enum { TUPLE_SIZE = std::tuple_size&amp;lt;Tuple&amp;gt;::value };&lt;br /&gt; &lt;br /&gt;   Tuple * tuple;&lt;br /&gt;   int current_;&lt;br /&gt;   int last_;&lt;br /&gt;   T * ref_;&lt;br /&gt;&lt;br /&gt;   T * update_ref()&lt;br /&gt;   {&lt;br /&gt;     if(current_ != last_)&lt;br /&gt;     {&lt;br /&gt;       ref_ = &amp;amp; TupleAt&amp;lt;Tuple&amp;gt;::get(*tuple, current_);&lt;br /&gt;       last_ = current_;&lt;br /&gt;     }&lt;br /&gt;     return ref_;&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;public:&lt;br /&gt;&lt;br /&gt;   typedef int difference_type;&lt;br /&gt;&lt;br /&gt;   explicit tuple_iterator(Tuple &amp;amp; t, int i = TUPLE_SIZE)&lt;br /&gt;     : tuple(&amp;amp;t),&lt;br /&gt;       current_(i),&lt;br /&gt;       last_(i-1),&lt;br /&gt;       ref_(&amp;amp;TupleAt&amp;lt;Tuple&amp;gt;::get(*tuple, last_))&lt;br /&gt;   {}&lt;br /&gt;   T &amp;amp; operator *() {&lt;br /&gt;     return *update_ref();&lt;br /&gt;   }&lt;br /&gt;   T * operator -&amp;gt;() {&lt;br /&gt;     return update_ref();&lt;br /&gt;   }&lt;br /&gt;   T &amp;amp; operator [] (int offset) {&lt;br /&gt;     return TupleAt&amp;lt;Tuple&amp;gt;::get(*tuple, current_+offset);&lt;br /&gt;   }&lt;br /&gt;   tuple_iterator &amp;amp; operator ++ () {&lt;br /&gt;     if(current_ &amp;lt; TUPLE_SIZE)&lt;br /&gt;       ++current_;&lt;br /&gt;     return *this;&lt;br /&gt;   }&lt;br /&gt;   tuple_iterator operator ++ (int) {&lt;br /&gt;     tuple_iterator temp(*this);&lt;br /&gt;     ++(*this);&lt;br /&gt;     return temp;&lt;br /&gt;   }&lt;br /&gt;   tuple_iterator &amp;amp; operator -- () {&lt;br /&gt;     if(current_ &amp;gt;= 0)&lt;br /&gt;       --current_;&lt;br /&gt;     return *this;&lt;br /&gt;   }&lt;br /&gt;   tuple_iterator operator -- (int) {&lt;br /&gt;     tuple_iterator temp(*this);&lt;br /&gt;     --(*this);&lt;br /&gt;     return temp;&lt;br /&gt;   }&lt;br /&gt;   tuple_iterator operator - (int i) const {&lt;br /&gt;     tuple_iterator temp(*tuple, current_-i);&lt;br /&gt;     return temp;&lt;br /&gt;   }&lt;br /&gt;   tuple_iterator &amp;amp; operator -= (int i) {&lt;br /&gt;     current_-=i;&lt;br /&gt;     return *this;&lt;br /&gt;   }&lt;br /&gt;   tuple_iterator operator + (int i) const {&lt;br /&gt;     tuple_iterator temp(*tuple, current_+i);&lt;br /&gt;     return temp;&lt;br /&gt;   }&lt;br /&gt;   tuple_iterator &amp;amp; operator += (int i) {&lt;br /&gt;     current_+=i;&lt;br /&gt;     return *this;&lt;br /&gt;   }&lt;br /&gt;   difference_type operator - (const tuple_iterator &amp;amp; ti) const {&lt;br /&gt;     return current_ - ti.current_;&lt;br /&gt;   }&lt;br /&gt;   bool operator &amp;lt; (const tuple_iterator &amp;amp;ti) const {&lt;br /&gt;     return index &amp;lt; ti.index;&lt;br /&gt;   }&lt;br /&gt;   bool operator &amp;gt; (const tuple_iterator &amp;amp;ti) const {&lt;br /&gt;     return index &amp;gt; ti.index;&lt;br /&gt;   }&lt;br /&gt;   bool operator &amp;lt;= (const tuple_iterator &amp;amp;ti) const {&lt;br /&gt;     return index &amp;lt;= ti.index;&lt;br /&gt;   }&lt;br /&gt;   bool operator &amp;gt;= (const tuple_iterator &amp;amp;ti) const {&lt;br /&gt;     return index &amp;gt;= ti.index;&lt;br /&gt;   }&lt;br /&gt;   bool operator == (tuple_iterator const &amp;amp; ti) const {&lt;br /&gt;     return (tuple == ti.tuple) &amp;amp;&amp;amp; (index == ti.index);&lt;br /&gt;   }&lt;br /&gt;   bool operator != (tuple_iterator const &amp;amp; ti) const {&lt;br /&gt;     return !(*this == ti);&lt;br /&gt;   }&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;template &amp;lt;&amp;gt;&lt;br /&gt;class tuple_iterator &amp;lt;std::tuple&amp;lt;&amp;gt;&amp;gt;&lt;br /&gt;{&lt;br /&gt; public:&lt;br /&gt;   tuple_iterator(std::tuple&amp;lt;&amp;gt;, size_t i = 0) {}&lt;br /&gt;};&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The tuple_iterator class provides the usual typedefs (e.g., difference_type, value_type, pointer, reference, and iterator_category) and overloaded operators (e.g., *, -&amp;gt;, [], +, -, +=, -=, -, +, &amp;lt;, &amp;gt;, &amp;lt;=, &amp;gt;=, ==, !=) to support the &lt;a href="http://www.cplusplus.com/reference/std/iterator"&gt;requirements of random access iterator&lt;/a&gt;. Just like tuple_array class it caches a pointer to the last element that was dereferenced. It goes through O(N) comparisons only if the tuple iterator is dereferenced at a different index than what is cached. A specialization of tuple_iterator for empty tuple is also provided. It has no members other than a constructor because there is nothing to dereference to!&lt;br /&gt;&lt;br /&gt;Finally, we need a way to create the begin and end iterator from a non-empty tuple. We add the corresponding functions.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;template &amp;lt;typename... Args&amp;gt;&lt;br /&gt;tuple_iterator &amp;lt;std::tuple&amp;lt;Args...&amp;gt;&amp;gt; begin(std::tuple &amp;lt;Args...&amp;gt; &amp;amp;t)&lt;br /&gt;{&lt;br /&gt; return tuple_iterator &amp;lt;std::tuple&amp;lt;Args...&amp;gt;&amp;gt;(t, 0);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;template &amp;lt;typename... Args&amp;gt;&lt;br /&gt;tuple_iterator &amp;lt;std::tuple&amp;lt;Args...&amp;gt;&amp;gt; end(std::tuple &amp;lt;Args...&amp;gt; &amp;amp;t)&lt;br /&gt;{&lt;br /&gt; return tuple_iterator &amp;lt;std::tuple&amp;lt;Args...&amp;gt;&amp;gt;(t);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;If no index is passed to the iterator constructor, it points to the &lt;span style="font-style:italic;"&gt;end&lt;/span&gt; of the tuple. The internal index of such an iterator is same as the size of the tuple. An iterator at the beginning has index = 0 -- the first element. Using the iterators is now straightforward. I do not discuss constant and reverse iterators here.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;int main(void)&lt;br /&gt;{&lt;br /&gt; auto tuple = std::make_tuple(10, 20, 30, 40);&lt;br /&gt; auto ta = make_tuple_array(4, 2, 1);&lt;br /&gt;&lt;br /&gt; std::copy(begin(tuple), end(tuple), std::ostream_iterator&amp;lt;int&amp;gt;(std::cout, " "));&lt;br /&gt; std::sort(begin(ta), end(ta));&lt;br /&gt;&lt;br /&gt; for(int i : ta)&lt;br /&gt; {&lt;br /&gt;   std::cout &amp;lt;&amp;lt; i &amp;lt;&amp;lt; std::endl;&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; return 0;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;I think, this rather naive exercise turned out to be quite interesting. Hopefully, you enjoyed as much as I did.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/13960885-1512032382027272749?l=cpptruths.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CppTruths/~4/9ORZhIukcp4" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://cpptruths.blogspot.com/feeds/1512032382027272749/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=13960885&amp;postID=1512032382027272749" title="4 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/1512032382027272749?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/1512032382027272749?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CppTruths/~3/9ORZhIukcp4/array-like-access-and-iterators-for.html" title="Array-like access and Iterators for Homogeneous Tuples" /><author><name>Sumant</name><uri>http://www.blogger.com/profile/11957855386259543653</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="28" height="32" src="http://4.bp.blogspot.com/--0WncXMeBPA/TchxRepk7bI/AAAAAAAABXo/oLNnYnw0K7A/s1600/Sumant-Tambe.JPG" /></author><thr:total>4</thr:total><feedburner:origLink>http://cpptruths.blogspot.com/2012/01/array-like-access-and-iterators-for.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DUYERnoyfyp7ImA9WhRUEUo.&quot;"><id>tag:blogger.com,1999:blog-13960885.post-7009828537901245933</id><published>2012-01-12T00:09:00.025-07:00</published><updated>2012-01-21T13:18:27.497-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-01-21T13:18:27.497-07:00</app:edited><title>General-purpose Automatic Memoization for Recursive Functions in C++11</title><content type="html">&lt;a href="http://en.wikipedia.org/wiki/Memoization"&gt;Memoization&lt;/a&gt; is a widely known optimization technique used primarily to speed up computer programs by having function calls avoid repeating the calculation of results for previously processed inputs. Repeated calculations are avoided by reusing previously computed results, which must be cached such that look-up is faster than recomputing.&lt;br /&gt;&lt;br /&gt;Consider a simple fibonacci program&lt;br /&gt;&lt;pre class="brush: cpp"&gt;unsigned long fibonacci(unsigned n)&lt;br /&gt;{&lt;br /&gt;  return (n &amp;lt; 2) ? n :  fibonacci(n - 1) + fibonacci(n - 2);&lt;br /&gt;}&lt;/pre&gt;This algorithm is a frustratingly slow way of computing the Nth fibonacci number (N starting at 0). It does a lot of redundant recomputations. But the beauty of this program is that it is really simple. To speed it up without changing its logic significantly, we could use memoization.&lt;br /&gt;&lt;br /&gt;Using some clever C++11 techniques, it is possible to memoize this function, which looks like below.&lt;br /&gt;&lt;pre class="brush: cpp"&gt;unsigned long fibonacci(unsigned n)&lt;br /&gt;{&lt;br /&gt;  return (n &amp;lt; 2) ? n :&lt;br /&gt;       memoized_recursion(fibonacci)(n - 1) +&lt;br /&gt;       memoized_recursion(fibonacci)(n - 2);&lt;br /&gt;} &lt;/pre&gt;To solve this problem, I took inspiration from &lt;a href="http://slackito.com/2011/03/17/automatic-memoization-in-cplusplus0x/"&gt;this&lt;/a&gt; post on automatic memoization. I'll go in lot more detail here including recursive functions and memory management. Here we go!&lt;br /&gt;&lt;br /&gt;The memoize function I'm using is slightly different than that of the post above.&lt;br /&gt;&lt;pre class="brush: cpp"&gt;template &amp;lt;typename ReturnType, typename... Args&amp;gt;&lt;br /&gt;std::function&amp;lt;ReturnType (Args...)&amp;gt;&lt;br /&gt;memoize(ReturnType (*func) (Args...))&lt;br /&gt;{&lt;br /&gt;  auto cache = std::make_shared&amp;lt;std::map&amp;lt;std::tuple&amp;lt;Args...&amp;gt;, ReturnType&amp;gt;&amp;gt;();&lt;br /&gt;  return ([=](Args... args) mutable  {&lt;br /&gt;          std::tuple&amp;lt;Args...&amp;gt; t(args...);&lt;br /&gt;          if (cache-&amp;gt;find(t) == cache-&amp;gt;end())&lt;br /&gt;              (*cache)[t] = func(args...);&lt;br /&gt;          return (*cache)[t];&lt;br /&gt;  });&lt;br /&gt;}&lt;/pre&gt;Function memoize accepts a pointer to a free function, wraps it in a lambda, and turns the lambda into a std::function. Returning a a std::function is a common C++11 idiom of returning a lambda from a function that creates it. The implementation of the lambda is pretty straight forward if you are familiar with C++11 &lt;a href="http://en.wikipedia.org/wiki/Variadic_template"&gt;variadic templates&lt;/a&gt;. It creates a tuple of arguments and checks if it exists in the cache. In that case, the stored result is returned instead of recomputing it. The cache used for mapping arguments to the return value, is allocated dynamically. A std::shared_ptr manages the memory. The lambda copies the std::shared_ptr by value. As long as there is at least one std::function&lt;returntype&gt; alive, the cache will remain intact.&lt;br /&gt;&lt;br /&gt;Memoized functions may be called from different places. It is quite cumbersome to pass the memoized function everywhere it is called. There should be a way to look up a memoized version of the function without loosing the state. So our next step is to make the same memoized function available from anywhere in the program. We need a map of function pointer to a memorized std::function. Specifically, we need a std::unordered_map for fast lookup.&lt;br /&gt;&lt;pre class="brush: cpp"&gt;template &amp;lt;typename F_ret, typename...  F_args&amp;gt;&lt;br /&gt;std::function&amp;lt;F_ret (F_args...)&amp;gt;&lt;br /&gt;memoized_recursion(F_ret (*func)(F_args...))&lt;br /&gt;{&lt;br /&gt;  typedef std::function&amp;lt;F_ret (F_args...)&amp;gt; FunctionType;&lt;br /&gt;  static std::unordered_map&amp;lt;decltype(func), FunctionType&amp;gt; functor_map;&lt;br /&gt;&lt;br /&gt;  if(functor_map.find(func) == functor_map.end())&lt;br /&gt;    functor_map[func] = memoize(func);&lt;br /&gt;&lt;br /&gt;  return functor_map[func];&lt;br /&gt;}&lt;/pre&gt;Here I introduce "memoized_recursion" function that our recursive fibonacci function is calling. It has a static std::unordered_map. It simply looks up the memorized std::function based on the function pointer value. If it does not find one, it creates it and stores it for subsequent access. Function pointers are unique; so there are no collisions possible. Here is how to call it.&lt;br /&gt;&lt;pre class="brush: cpp"&gt;memorized_recursion(fibonacci)(10);&lt;/pre&gt;The solution is not finished yet though. Memoization obviously builds up state very fast. If many functions are memoized with a large number of parameters, the state grows explosively. There must be some way to reclaim the memory.&lt;br /&gt;&lt;br /&gt;Remember that the memoized state grows in the lambda. The dynamically allocated map stores the cache for corresponding function. We need to access the object that is hidden inside a lambda. Lambda has a compiler-defined type and only thing you can do with it is call it. So how would we clear the cache it is building up?&lt;br /&gt;&lt;br /&gt;The answer is surprisingly simple! Just assign the memoizer (the lambda) with another default initialized memoizer.&lt;br /&gt;&lt;br /&gt;We already have memoize function, which returns a default initialized memoizer. We simply assign the new one in place of the old one. Here’s how the new memoized_recursion looks like&lt;br /&gt;&lt;pre class="brush: cpp"&gt;enum class Cache : unsigned int { NO_RECLAIM, RECLAIM };&lt;br /&gt;&lt;br /&gt;template &amp;lt;typename F_ret, typename... F_args&amp;gt;&lt;br /&gt;std::function&amp;lt;F_ret (F_args...)&amp;gt;&lt;br /&gt;memoized_recursion(F_ret (*func)(F_args...), Cache c = Cache::NO_RECLAIM)&lt;br /&gt;{&lt;br /&gt;  typedef std::function&amp;lt;F_ret (F_args...)&amp;gt; FunctionType;&lt;br /&gt;  static std::unordered_map&amp;lt;decltype(func), FunctionType&amp;gt; functor_map;&lt;br /&gt;&lt;br /&gt;  if(Cache::RECLAIM == c)&lt;br /&gt;    return functor_map[func] = memoize(func);&lt;br /&gt;&lt;br /&gt;  if(functor_map.find(func) == functor_map.end())&lt;br /&gt;    functor_map[func] = memoize(func);&lt;br /&gt;&lt;br /&gt;  return functor_map[func];&lt;br /&gt;}&lt;/pre&gt;I’m using strongly typed enums to pass programmer’s intent to clear the cache. Here is how you call it.&lt;br /&gt;&lt;pre class="brush: cpp"&gt;memoized_recursion(fibonacci, Cache::RECLAIM);&lt;/pre&gt;&lt;br /&gt;&lt;h3&gt;Purely Static Memoizer&lt;/h3&gt;&lt;br /&gt;Strictly speaking, using an std::unordered_map in memoized_recursion function is not necessary. It is an O(1) mapping of function pointers to their corresponding memoized function objects (lambda wrapped in a std::function). An alternative way of achieving the same mapping is using purely static memoizer. I call it &lt;span style="font-style:italic;"&gt;pure&lt;/span&gt; because there is no dynamic allocation like in std::unordered_map. The functors are stored as static objects only. This is possible only if memoized_recursion can be specialized individually for &lt;u&gt;&lt;span style="font-style:italic;"&gt;all possible free functions&lt;/span&gt;&lt;/u&gt;! Note that each free function is guaranteed to have a unique pointer value and pointer values can be used as template parameters. So here is how to combine all these things in a &lt;span style="font-weight:bold;"&gt;static_memoizer&lt;/span&gt;.&lt;br /&gt;&lt;pre class="brush: cpp"&gt;template &amp;lt;typename Sig, Sig funcptr&amp;gt;&lt;br /&gt;struct static_memoizer;&lt;br /&gt;&lt;br /&gt;template &amp;lt;typename F_ret, typename... F_args, F_ret (*func)(F_args...)&amp;gt;&lt;br /&gt;struct static_memoizer&amp;lt;F_ret (*)(F_args...), func&amp;gt;&lt;br /&gt;{&lt;br /&gt;  static &lt;br /&gt;  std::function&amp;lt;F_ret (F_args...)&amp;gt; &amp; &lt;br /&gt;  get(Cache c = Cache::NO_RECLAIM)&lt;br /&gt;  {&lt;br /&gt;    static std::function&amp;lt;F_ret (F_args...)&amp;gt; mfunc (memoize(func));&lt;br /&gt;&lt;br /&gt;    if(Cache::RECLAIM == c)&lt;br /&gt;      mfunc = memoize(func);&lt;br /&gt;&lt;br /&gt;    return mfunc;&lt;br /&gt;  }&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;#define STATIC_MEMOIZER(func) static_memoizer&amp;lt;decltype(&amp;func), &amp;func&amp;gt;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The STATIC_MEMOIZER macro simplifies the use of the static_memoizer. It extracts the type of the function pointer using decltype and passes it (the type) as the first parameter of the template. The second parameter is the actual function pointer. Passing the function pointer as a template parameter is important because many functions potentially share the same signature but never the same pointer.&lt;br /&gt;&lt;br /&gt;The static objects used by the static_memoizer are different from that of memoized_recursion. So we've to rewrite the fibonacci function to use the static_memoizer.&lt;br /&gt;&lt;pre class="brush: cpp"&gt;unsigned long fibonacci(unsigned n)&lt;br /&gt;{&lt;br /&gt;  return (n &amp;lt; 2) ? n :&lt;br /&gt;       STATIC_MEMOIZER(fibonacci)::get()(n - 1) +&lt;br /&gt;       STATIC_MEMOIZER(fibonacci)::get()(n - 2);&lt;br /&gt;} &lt;/pre&gt; That's all for now. I hope you enjoyed it.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/13960885-7009828537901245933?l=cpptruths.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CppTruths/~4/XHjv3Q4N7wY" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://cpptruths.blogspot.com/feeds/7009828537901245933/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=13960885&amp;postID=7009828537901245933" title="11 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/7009828537901245933?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/7009828537901245933?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CppTruths/~3/XHjv3Q4N7wY/general-purpose-automatic-memoization.html" title="General-purpose Automatic Memoization for Recursive Functions in C++11" /><author><name>Sumant</name><uri>http://www.blogger.com/profile/11957855386259543653</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="28" height="32" src="http://4.bp.blogspot.com/--0WncXMeBPA/TchxRepk7bI/AAAAAAAABXo/oLNnYnw0K7A/s1600/Sumant-Tambe.JPG" /></author><thr:total>11</thr:total><feedburner:origLink>http://cpptruths.blogspot.com/2012/01/general-purpose-automatic-memoization.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CkUMRXY5fyp7ImA9WhRVFEk.&quot;"><id>tag:blogger.com,1999:blog-13960885.post-9145173853304789405</id><published>2011-10-11T21:59:00.012-06:00</published><updated>2012-01-13T00:38:04.827-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-01-13T00:38:04.827-07:00</app:edited><title>Multi-dimensional arrays in C++11</title><content type="html">What new can be said about multi-dimensional arrays in C++? As it turns out, quite a bit! With the advent of C++11, we get new standard library class std::array. We also get new language features, such as template aliases and variadic templates. So I'll talk about interesting ways in which they come together.&lt;br /&gt;&lt;br /&gt;It all started with a simple question of how to define a multi-dimensional std::array. It is a great example of &lt;span style="font-style:italic;"&gt;deceptively simple&lt;/span&gt; things. Are the following the two arrays identical except that one is native and the other one is std::array?&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;int native[3][4];&lt;br /&gt;std::array&amp;lt;std::array&amp;lt;int, 3&amp;gt;, 4&amp;gt; arr;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;No! They are not. In fact, arr is more like an int[4][3]. Note the difference in the array subscripts. The native array is an array of 3 elements where every element is itself an array of 4 integers. 3 rows and 4 columns. If you want a std::array with the same layout, what you really need is:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;std::array&amp;lt;std::array&amp;lt;int, 4&amp;gt;, 3&amp;gt; arr;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;That's quite annoying for two reasons. First of all, it is quite verbose. Think of three or higher dimensional arrays. It's just ugly. Worse yet, the array bounds must be spelled out in reverse order.&lt;br /&gt;&lt;br /&gt;Fear not, help is on its way! Meet &lt;a href="http://en.wikipedia.org/wiki/C%2B%2B11#Template_aliases"&gt;template aliases&lt;/a&gt;! It is a way of defining synonyms for other types including partially defined templates. With C++03 typedef, you must use a fully specialized template to create an alias. C++11 still has that restriction on typedefs but template aliases will let you create "typedefs" for template partial specializations. It is a C++11 solution for the &lt;a href="http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Type_Generator"&gt;Templated Typedef&lt;/a&gt; idiom. Lets try to write one for a two dimensional std::array.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;template &amp;lt;class T, size_t ROW, size_t COL&amp;lt;&lt;br /&gt;using Matrix = std::array&amp;lt;std::array&amp;lt;T, COL&amp;gt;, ROW&amp;gt;;&lt;br /&gt;Matrix&amp;lt;float, 3, 4&amp;gt; mat;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;This one is much nicer. Matrix is a template alias for a partial specialization of std::array. With that, defining a two dimensional matrix (mat) is really easy. Note that order of ROW and COL. An alias for two dimensional native array can also be defined similarly.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;template &amp;lt;class T, size_t ROW, size_t COL&amp;gt;&lt;br /&gt;using NativeMatrix = T[ROW][COL];&lt;br /&gt;NativeMatrix&amp;lt;float, 3, 4&amp;gt; mat;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;So far so good. Lets move on to multi-dimensional arrays. Using template aliases for arbitrary dimension arrays would need variadic templates. Unfortunately, it is not straightforward at all.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;template &amp;lt;class T, size_t... DIMS&amp;gt;&lt;br /&gt;using MultiDimArray = std::array&amp;lt;??? ...DIMS... ???&amp;gt;;&lt;br /&gt;MultiDimArray&amp;lt;float, 3, 4, 5 , 6, 7&amp;gt; floats;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;DIMS parameter pack can be expanded where a comma separated list is expected. However, multi-dimensional std::array definitions are &lt;span style="font-weight:bold;"&gt;hierarchical&lt;/span&gt;, which prevents straight-forward parameter pack expansion.&lt;br /&gt;&lt;br /&gt;One way I could make it work was using a little meta-program.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;template &amp;lt;class T, size_t I, size_t... J&amp;gt;&lt;br /&gt;struct MultiDimArray &lt;br /&gt;{&lt;br /&gt;  using Nested = typename MultiDimArray&amp;lt;T, J...&amp;gt;::type;&lt;br /&gt;  // typedef typename MultiDimArray&amp;lt;T, J...&amp;gt;::type Nested;&lt;br /&gt;  using type = std::array&amp;lt;Nested, I&amp;gt;;&lt;br /&gt;  // typedef std::array&amp;lt;Nested, I&amp;gt; type;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;template &amp;lt;class T, size_t I&amp;gt;&lt;br /&gt;struct MultiDimArray&amp;lt;T, I&amp;gt; &lt;br /&gt;{&lt;br /&gt;  using type = std::array&amp;lt;T, I&amp;gt;;&lt;br /&gt;  // typedef std::array&amp;lt;T, I&amp;gt; type;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;MultiDimArray&amp;lt;float, 3, 4, 5, 6, 7&amp;gt;::type floats;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;MultiDimArray is a pair of meta-functions to compute nested type for multi-dimensional std::array. The most general MultiDimArray is a variadic template of unsigned integers to pass an arbitrary number of dimensions. The terminating MultiDimArray specialization defines the simplest case of single dimensional std::array. I'm using the "using" syntax instead of typedefs. The equivalent typedef are written in comments.&lt;br /&gt;&lt;br /&gt;Similarly, MultiDimNative can also defined to create a native array of arbitrary dimensions.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;template &amp;lt;class T, size_t I, size_t... J&amp;gt;&lt;br /&gt;struct MultiDimNative &lt;br /&gt;{&lt;br /&gt;  using Nested = typename MultiDimNative&amp;lt;T, J...&amp;gt;::type;&lt;br /&gt;  using type = Nested [I];&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;template &amp;lt;class T, size_t I&amp;gt;&lt;br /&gt;struct MultiDimNative&amp;lt;T, I&amp;gt; &lt;br /&gt;{&lt;br /&gt;  using type = T [I];&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;MultiDimNative&amp;lt;double, 3, 4, 5, 6, 7&amp;gt;::type doubles;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;To make sure that the layout of all the arrays is the same I wrote a small test program.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;template &amp;lt;class T, size_t I, size_t J&amp;gt;&lt;br /&gt;union data&lt;br /&gt;{&lt;br /&gt;  T native[I][J];&lt;br /&gt;  NativeMatrix&amp;lt;T, I, J&amp;gt; native_matrix;&lt;br /&gt;  Matrix&amp;lt;T, I, J&amp;gt; matrix;&lt;br /&gt;  typename MultiDimArray&amp;lt;T, I, J&amp;gt;::type multidim_array;&lt;br /&gt;  typename MultiDimNative&amp;lt;T, I, J&amp;gt;::type multidim_native;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;template &amp;lt;class T&amp;gt;&lt;br /&gt;void print(T &amp;amp; t, size_t rows, size_t columns)&lt;br /&gt;{&lt;br /&gt;  for(size_t i = 0;i &amp;lt; rows; ++i)&lt;br /&gt;  {&lt;br /&gt;    for(size_t j = 0;j &amp;lt; columns; ++j)&lt;br /&gt;      printf("%d ", t[i][j]);&lt;br /&gt;&lt;br /&gt;    printf("\n");&lt;br /&gt;  }&lt;br /&gt;  printf("\n");&lt;br /&gt;}&lt;br /&gt;int main()&lt;br /&gt;{&lt;br /&gt;  constexpr size_t I = 3;&lt;br /&gt;  constexpr size_t J = 4;&lt;br /&gt;&lt;br /&gt;  data&amp;lt;int, I, J&amp;gt; d;&lt;br /&gt;  size_t val = 0;&lt;br /&gt;&lt;br /&gt;  for(size_t i = 0;i &amp;lt; I; ++i)&lt;br /&gt;  {&lt;br /&gt;    for(size_t j = 0;j &amp;lt; J; ++j)&lt;br /&gt;      d.native[i][j] = val++;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  print(d.native, I, J);&lt;br /&gt;  print(d.native_matrix, I, J);&lt;br /&gt;  print(d.matrix, I, J);&lt;br /&gt;  print(d.multidim_array, I, J);&lt;br /&gt;  print(d.multidim_native, I, J);&lt;br /&gt;&lt;br /&gt;  return 0;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;This program defines a union of 5 different arrays, all of which have the same dimensions and layout. It populates a native two dimensional array and prints the contents using all other multi-dimensional arrays defined in the same union. As of today, only clang accepts this program.&lt;br /&gt;&lt;br /&gt;That's it for now!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/13960885-9145173853304789405?l=cpptruths.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CppTruths/~4/xLQSVzzU59I" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://cpptruths.blogspot.com/feeds/9145173853304789405/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=13960885&amp;postID=9145173853304789405" title="13 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/9145173853304789405?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/9145173853304789405?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CppTruths/~3/xLQSVzzU59I/multi-dimensional-arrays-in-c11.html" title="Multi-dimensional arrays in C++11" /><author><name>Sumant</name><uri>http://www.blogger.com/profile/11957855386259543653</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="28" height="32" src="http://4.bp.blogspot.com/--0WncXMeBPA/TchxRepk7bI/AAAAAAAABXo/oLNnYnw0K7A/s1600/Sumant-Tambe.JPG" /></author><thr:total>13</thr:total><feedburner:origLink>http://cpptruths.blogspot.com/2011/10/multi-dimensional-arrays-in-c11.html</feedburner:origLink></entry><entry gd:etag="W/&quot;C04FQXk8eCp7ImA9WhRVFEk.&quot;"><id>tag:blogger.com,1999:blog-13960885.post-210676889653078407</id><published>2011-09-03T15:22:00.018-06:00</published><updated>2012-01-13T01:05:10.770-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-01-13T01:05:10.770-07:00</app:edited><title>A tale of noexcept swap for user-defined classes in C++11</title><content type="html">C++11 has taken another stab at function exception specifications for the masses. The shiny new ‘noexcept’ keyword is phasing out its zombie cousin ‘throw’. The &lt;a href="http://www.gotw.ca/publications/mill22.htm"&gt;well accepted guideline&lt;/a&gt; for the old exception specification is: "don’t use them!" That’s good for us because now we don’t have to bother (the reasons for not using throw specification aren’t for the faint hearted anyways.) The noexcept feature does not appear to be a walk in a park either. So hold on tight!&lt;br /&gt;&lt;br /&gt;noexcept is meta-programmable! a.k.a conditional noexcept. It is possible to conditionally specify functions to throw any exceptions. The noexcept specification of functions can be inspected at compile-time and functions can derive their own noexcept specification based on exception specifications found elsewhere in the program. Meta-programs are not off-limits here. An excellent introduction of the noexcept feature and its history can be found in &lt;a href="http://accu.org/index.php/journals/c297/"&gt;June’11 Overload Journal&lt;/a&gt; and on &lt;a href="http://akrzemi1.wordpress.com/2011/06/10/using-noexcept/"&gt;Andrzej's C++ blog&lt;/a&gt;. I won’t repeat that here but a quick motivation is in order.&lt;br /&gt;&lt;br /&gt;Compile-time knowledge about a move-constructor that it does not throw (i.e., annotated with noexcept(true)) can be used for improved run-time performance. For example, std::vector&amp;lt;T&amp;gt;::resize, std::vector&amp;lt;T&amp;gt;::reserve automatically use T’s move-constructor instead of a copy-constructor if T's move-constructor does not throw. Moving of T objects instead of copying would likely achieve higher performance. The standard library provides std::move_if_noexcept function that does move only if it is guaranteed to not fail. Otherwise, it simply resorts to copy-construction. More on this can be found &lt;a href="http://cpp-next.com/archive/2009/10/exceptionally-moving/"&gt;here&lt;/a&gt;. I'll return to the topic of writing noexcept move-ctor towards the end of this post. &lt;br /&gt;&lt;br /&gt;But the post is about swapping, so lets talk about that. Here is how the std::pair::swap is declared in C++11.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;void pair::swap(pair&amp;amp; p)&lt;br /&gt;  noexcept(noexcept(swap(first, p.first)) &amp;amp;&amp;amp;&lt;br /&gt;           noexcept(swap(second, p.second)));&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;It basically says that pair's swap will throw if either swapping of first or second member throws. The swapping of first and second possibly resolve to their own namespace-level swap via ADL or else they simply pick up std::swap (because pair::swap is declared in std namespace). This declaration seems to indicate a few things. &lt;br /&gt;&lt;br /&gt;&lt;ol&gt;&lt;li&gt;For a user-defined type it is now much more preferable to have its own namespace-level swap overload instead of using vanilla std::swap. The namespace-level swap function, being an extension of the type’s interface, is vastly more efficient and often can be written in way that it does not throw. The std::swap function, on the other hand, may throw because it uses a copy-constructor and copy-assignment operator while swapping two objects. If you are like me, your member copy-assignment operator will use &lt;a href="http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Copy-and-swap"&gt;copy-and-swap idiom&lt;/a&gt; for strong exception safety. That means std::swap will create and destroy 3 copies. What a waste! Moreover, that increases the chance of throwing. Bottom line: If T has a member swap, a swap function should be added in the same namespace as of T. &lt;/li&gt;&lt;br /&gt;&lt;li&gt;There are some assumptions buried in the above reasoning: (1) move-constructor is not available for a user-defined T, and (2) it is possible to implement member swap of T that does not throw and you can actually say so. &lt;/li&gt;&lt;br /&gt;&lt;li&gt;As far as move-constructor being not available is concerned, I think, there are large number of C++03 libraries, which will acquire move-semantics slowly than you might desire. Till then std::swap will, unfortunately, use copy-ctor and copy-assign. A legacy class with a copy-ctor won’t get an automatic move-ctor because it would do wrong things.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;The noexcept specification of the user-defined swap better be accurate. Can we really write a nothrow member swap and say so confidently? Obviously, it depends on the members of the user-defined type that we’re swapping. To me, it’s all uphill from here. &lt;/li&gt;&lt;/ol&gt;&lt;br /&gt;&lt;br /&gt;Lets look at how standard library uses noexcept for some of its own classes. We already saw std::pair before. How about std::tuple, which is a generalization of a struct and that’s why may be user-defined classes should follow the same basic principle. Tuple’s member swap is declared as&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;void tuple::swap(tuple&amp;amp; rhs) noexcept(see below)&lt;br /&gt;// The expression inside noexcept is equivalent to the&lt;br /&gt;// logical AND of the following expressions:&lt;br /&gt;&lt;br /&gt;noexcept(swap(declval&amp;lt;T&amp;amp;&amp;gt;(), declval&amp;lt;T&amp;amp;&amp;gt;()))&lt;br /&gt;// where Ti is ith type in the variadic list of types.&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Tuple’s member swap inspects the noexcept specifications of its members’ swap functions and derives its own specification from that. That makes sense. If swapping of any of the member throws, the tuple’s swap throws. The declval function belongs to same clique as std::move, std::forward, etc. It is a way to obtain rvalue reference of a type without using a constructor. It suffices to say that declval&amp;lt;T&amp;gt; returns "T&amp;amp;&amp;amp;" and declval&amp;lt;T&amp;amp;&amp;gt; returns "T &amp;amp; &amp;amp;&amp;amp;", which is the same as "T &amp;amp;." &lt;br /&gt;&lt;br /&gt;Consider a typical C++03 user-defined legacy class that manages its own resources.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;namespace L &lt;br /&gt;{&lt;br /&gt;struct legacy &lt;br /&gt;{&lt;br /&gt;  legacy();                             // Does not throw&lt;br /&gt;  legacy(const legacy &amp;);               // This may throw&lt;br /&gt;  legacy &amp; operator = (const legacy &amp;); // This may throw (strong exception safe)&lt;br /&gt;  ~legacy() throw();                    // Does not throw&lt;br /&gt;  void swap(legacy &amp;) throw();          // Does not throw&lt;br /&gt;};&lt;br /&gt;} // namespace L&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The above legacy class is well-designed except for the fact that it does not have any namespace-level swap. To make it a better citizen in C++11, it needs a namespace-level swap. Interestingly enough, there is substantial &lt;a href="http://stackoverflow.com/questions/11562/how-to-overload-stdswap"&gt;code &lt;/a&gt;out there that has a specialization of the std::swap in the std namespace. Considering the popularity of this anti-pattern, it probably makes sense to add a swap in two places. It is not too much work in the first place and that may help people who always use a qualified swap (std::swap) habitually.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;namespace L &lt;br /&gt;{&lt;br /&gt;  void swap(legacy &amp;, legacy &amp;) noexcept;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;namespace std &lt;br /&gt;{&lt;br /&gt;  template &amp;lt;&amp;gt;&lt;br /&gt;  void swap(L::legacy &amp;, L::legacy &amp;) noexcept;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Let’s try to use this modernized legacy class in our C++11 class: Modern.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;namespace M &lt;br /&gt;{&lt;br /&gt;struct Modern &lt;br /&gt;{&lt;br /&gt;  int count;&lt;br /&gt;  std::string str;&lt;br /&gt;  std::array&amp;lt;L::legacy, 5&amp;gt; data;&lt;br /&gt;  /// default-ctor, copy-ctor, copy-assign, move-ctor, move-assign are defined = default.&lt;br /&gt;  void swap(Modern &amp; p) &lt;br /&gt;    noexcept(noexcept(swap(std::declval&amp;lt;int &amp;&amp;gt;(),&lt;br /&gt;                           std::declval&amp;lt;int &amp;&amp;gt;())) &amp;&amp;&lt;br /&gt;             noexcept(swap(std::declval&amp;lt;std::string &amp;&amp;gt;(),&lt;br /&gt;                           std::declval&amp;lt;std::string &amp;&amp;gt;())) &amp;&amp;&lt;br /&gt;             noexcept(swap(std::declval&amp;lt;std::array&amp;lt;L::legacy, 5&amp;gt; &amp;&amp;gt;(),&lt;br /&gt;                           std::declval&amp;lt;std::array&amp;lt;L::legacy, 5&amp;gt; &amp;&amp;gt;())));&lt;br /&gt;};&lt;br /&gt;} // namespace M&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;That’s one awful looking swap. My eyes bleed when I look at it. &lt;br /&gt;&lt;br /&gt;It is doing exactly the same thing as std::tuple. It simply checks whether swapping two integers, two strings, and two arrays throw or not. If it does, then member swap of Modern throws.  You can skip checks for integer swapping but what’s left is not pretty at all.&lt;br /&gt;&lt;br /&gt;Couple of important things to note here: &lt;ol&gt;&lt;li&gt;Because we added namespace-level swap for the L::legacy class, we dodged several problems.If we did not have free swap, the compiler will instantiate std::swap if it is in the scope. Note, however, that vanilla std::swap may throw defeating the purpose of Modern::swap. If no swap is to be found, compiler issues an error.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;We hope that swap of std::string and std::array do not throw. As mentioned in [container.requirements.general], std::string::swap does not throw but std::array&amp;lt;T&amp;gt; swap may throw if an unqualified call to swap(T &amp;amp;, T &amp;amp;) throws. Once again, the namespace-level swap will be chosen here, if available. If that does not exist, a specialization of std::swap will be chosen. If none of them exist, std::swap will be instantiated giving our Modern::swap a nothrow(false) specification.&lt;/li&gt;&lt;/ol&gt;&lt;br /&gt;I like my strong exception safety in my little copy-assignment operator so I don’t want my swap to throw but I don’t want my program to std::terminate() if an exception is really thrown. With all that in mind, I would rewrite the swap as follows.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;void Modern::swap(Modern &amp;) noexcept &lt;br /&gt;{&lt;br /&gt;  static_assert(noexcept(swap(std::declval&amp;lt;int &amp;&amp;gt;(),&lt;br /&gt;                              std::declval&amp;lt;int &amp;&amp;gt;())) &amp;&amp;&lt;br /&gt;                noexcept(swap(std::declval&amp;lt;std::string &amp;&amp;gt;(),&lt;br /&gt;                              std::declval&amp;lt;std::string &amp;&amp;gt;())) &amp;&amp;&lt;br /&gt;                noexcept(swap(std::declval&amp;lt;std::array&amp;lt;L::legacy, 5&amp;gt; &amp;&amp;gt;(),&lt;br /&gt;                              std::declval&amp;lt;std::array&amp;lt;L::legacy, 5&amp;gt; &amp;&amp;gt;())), &lt;br /&gt;                "throwing swap");&lt;br /&gt;  //.... remaining swap code&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This is not unlike what’s &lt;a href="http://akrzemi1.wordpress.com/2011/06/10/using-noexcept/"&gt;proposed by others&lt;/a&gt; but there’s more. The static assert looks awful and looks redundant. There is already a standard library utility that does the same thing: std::tuple. As mentioned before, std::tuple’s swap throws if any member swap throws. We use it here to make our job a lot easier.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;void Modern::swap(Modern &amp; that) noexcept &lt;br /&gt;{&lt;br /&gt;  typedef std::tuple&amp;lt;int, std::string, std::array &amp;lt;L::legacy, 5&amp;gt; &amp;gt; MemberTuple;&lt;br /&gt;  static MemberTuple *t = 0;&lt;br /&gt;  static_assert(noexcept(t-&gt;swap(*t)), "throwing swap");&lt;br /&gt;  // .... remaining swap code&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;If you an enthusiastically paranoid C++ programmer, you may want to use conditional noexcept with a little meta-function (&lt;span style="font-style:italic;"&gt;is_nothrow_swappable_all&lt;/span&gt;) to save typing.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;template&amp;lt;typename... T&amp;gt;&lt;br /&gt;struct is_nothrow_swappable_all&lt;br /&gt;{&lt;br /&gt;  static std::tuple&amp;lt;T...&amp;gt; *t = 0;&lt;br /&gt;  enum { value = noexcept(t-&amp;gt;swap(*t)) };&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;void Modern::swap(Modern &amp; that) &lt;br /&gt;   noexcept(is_nothrow_swappable_all&amp;lt;int, std::string, std::array&amp;lt;L::legacy, 5&amp;gt; &amp;gt;::value);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The "remaining swap code" section above is also rather important. The &lt;a href="http://stackoverflow.com/questions/11562/how-to-overload-stdswap"&gt;recommended&lt;/a&gt; (by Dave and Howard) way to write it is to use unqualified swap but bring std::swap in the scope:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;void Modern::swap(Modern &amp; that) &lt;br /&gt;  noexcept(is_nothrow_swappable_all&amp;lt;int, std::string, std::array&amp;lt;L::legacy, 5&amp;gt; &amp;gt;::value);&lt;br /&gt;{&lt;br /&gt;  using std::swap;&lt;br /&gt;  swap(this-&amp;gt;count, that-&amp;gt;count);&lt;br /&gt;  swap(this-&amp;gt;str, that-&amp;gt;str);&lt;br /&gt;  swap(this-&amp;gt;data, that-&amp;gt;data);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The appropriate swap (namespace-level via ADL or std::swap) will be chosen depending upon availability. That’s exactly what tuple’s swap noexcept checker is going to do for us.&lt;br /&gt;&lt;br /&gt;Back to the move-constructor, as promised! As mentioned before, noexcept specification of a move-ctor may have performance implications. So you want to get it right. For the M::Modern class we could have defaulted the move-ctor (= default). That will give it a noexcept(false) specification automatically because internally it uses L::legacy’s copy constructor, which throws. As a consequence, std::vector&lt;M::Modern&gt;::resize is not as fast as it can be. We can do better. &lt;br /&gt;&lt;br /&gt;Implementing a move-ctor using the default-construct-and-swap idiom turns out be quite handy. Default-construct-and-swap does what it says by first delegating to a noexcept default constructor followed by a swap. To implement a noexcept move-ctor this way, you really need to make sure that swap does not throw. As always, you can rely on a conditional noexcept. I'm using std::is_nothrow_constructible type trait to test the obvious!&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;Modern::Modern(Modern &amp;&amp; m) &lt;br /&gt;  noexcept(std::is_nothrow_constructible&amp;lt;Modern&gt;::value &amp;&amp;&lt;br /&gt;           noexcept(m.swap(m)))&lt;br /&gt;  : Modern()           &lt;br /&gt;{&lt;br /&gt;  swap(m);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;As long as Modern's default constructor and member swap are noexcept, the move-ctor is noexcept.&lt;br /&gt;&lt;br /&gt;Finally, the move-assign operator can be simply implemented as a single swap operation but for &lt;a href="http://stackoverflow.com/questions/6687388/why-do-some-people-use-swap-for-move-assignments"&gt;some classes&lt;/a&gt; that may not be accurate. &lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;Modern::operator = (Modern &amp;&amp; m) noexcept&lt;br /&gt;{&lt;br /&gt;  swap(m);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Acknowledgements: I want to thank Howard Hinnant (former Library Working Group chair) for reviewing this article and providing me valuable feedback. Any inaccuracies and mistakes left in the article are strictly mine.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/13960885-210676889653078407?l=cpptruths.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CppTruths/~4/lI98nU49YVc" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://cpptruths.blogspot.com/feeds/210676889653078407/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=13960885&amp;postID=210676889653078407" title="5 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/210676889653078407?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/210676889653078407?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CppTruths/~3/lI98nU49YVc/tale-of-noexcept-swap-for-user-defined.html" title="A tale of noexcept swap for user-defined classes in C++11" /><author><name>Sumant</name><uri>http://www.blogger.com/profile/11957855386259543653</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="28" height="32" src="http://4.bp.blogspot.com/--0WncXMeBPA/TchxRepk7bI/AAAAAAAABXo/oLNnYnw0K7A/s1600/Sumant-Tambe.JPG" /></author><thr:total>5</thr:total><feedburner:origLink>http://cpptruths.blogspot.com/2011/09/tale-of-noexcept-swap-for-user-defined.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CEcHRXo4cCp7ImA9WhRVFEk.&quot;"><id>tag:blogger.com,1999:blog-13960885.post-7799526502984979145</id><published>2011-07-26T13:10:00.003-06:00</published><updated>2012-01-13T01:07:14.438-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-01-13T01:07:14.438-07:00</app:edited><title>Compile-time regex matcher using constexpr</title><content type="html">With my growing constexpr fascination, I thought of using it for something that would be really hard using template meta-programs. How about implementing a compile-time regular expression matcher? Fortunately, a simple regular expression matcher has already been written by &lt;a href="http://www.cs.princeton.edu/courses/archive/spr09/cos333/beautiful.html"&gt;Rob Pike&lt;/a&gt;. I just rewrote it using constexpr: single return statement in functions, no modifications to the parameters, abundant ternery operators, and recursion. Here we go...&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;constexpr int match_c(const char *regexp, const char *text);&lt;br /&gt;constexpr int matchhere_c(const char *regexp, const char *text);&lt;br /&gt;constexpr int matchstar_c(int c, const char *regexp, const char *text);&lt;br /&gt;constexpr int matchend_c(const char * regexp, const char * text);&lt;br /&gt;&lt;br /&gt;constexpr int matchend_c(const char * regexp, const char * text)&lt;br /&gt;{&lt;br /&gt;  return matchhere_c(regexp, text) ? 1 : &lt;br /&gt;         (*text == '\0') ? 0 : matchend_c(regexp, text+1);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;constexpr int match_c(const char *regexp, const char *text)&lt;br /&gt;{&lt;br /&gt;  return (regexp[0] == '^') ? matchhere_c(regexp+1, text) : &lt;br /&gt;                              matchend_c(regexp, text);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;/* matchhere: search for regexp at beginning of text */&lt;br /&gt;constexpr int matchhere_c(const char *regexp, const char *text)&lt;br /&gt;{&lt;br /&gt;  return (regexp[0] == '\0') ? 1 : &lt;br /&gt;         (regexp[1] == '*') ? matchstar_c(regexp[0], regexp+2, text) :&lt;br /&gt;         (regexp[0] == '$' &amp;&amp; regexp[1] == '\0') ? (*text == '\0') :&lt;br /&gt;         (*text!='\0' &amp;&amp; (regexp[0]=='.' || regexp[0]==*text)) ? &lt;br /&gt;          matchhere_c(regexp+1, text+1) : 0;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;/* matchstar: search for c*regexp at beginning of text */&lt;br /&gt;constexpr int matchstar_c(int c, const char * regexp, const char *text)&lt;br /&gt;{&lt;br /&gt;  return matchhere_c(regexp, text) ? 1 : &lt;br /&gt;         (*text != '\0' &amp;&amp; (*text == c || c == '.')) ? &lt;br /&gt;           matchstar_c(c, regexp, text+1) : 0;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;#define TO_STR_IMPL(R) #R&lt;br /&gt;#define TO_STR(R) TO_STR_IMPL(R)&lt;br /&gt;&lt;br /&gt;int main(void)&lt;br /&gt;{&lt;br /&gt;  static_assert(match_c(TO_STR(REGEX), TO_STR(TEXT)), "...");&lt;br /&gt;&lt;br /&gt;  return 0;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;To compile it, as of today, you need g++ 4.6 or better. You've to pass REGEX and TEXT as #defines while compilation. For instance, -D REGEX=o$ -D TEXT=Foo It matches! &lt;br /&gt;&lt;br /&gt;I used two macros TO_STR and To_STR_IMPL to convert the REGEX and TEXT into string literals. #R is basically using the preprocessor stringification technique. For some reason I need two separate TO_STR macros for TEXT substitution and stringification. Seems like the gcc preprocessor can't do those two things in a single macro. &lt;br /&gt;&lt;br /&gt;Have fun!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/13960885-7799526502984979145?l=cpptruths.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CppTruths/~4/jXWdDnW5kGg" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://cpptruths.blogspot.com/feeds/7799526502984979145/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=13960885&amp;postID=7799526502984979145" title="4 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/7799526502984979145?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/7799526502984979145?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CppTruths/~3/jXWdDnW5kGg/compile-time-regex-matcher-using.html" title="Compile-time regex matcher using constexpr" /><author><name>Sumant</name><uri>http://www.blogger.com/profile/11957855386259543653</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="28" height="32" src="http://4.bp.blogspot.com/--0WncXMeBPA/TchxRepk7bI/AAAAAAAABXo/oLNnYnw0K7A/s1600/Sumant-Tambe.JPG" /></author><thr:total>4</thr:total><feedburner:origLink>http://cpptruths.blogspot.com/2011/07/compile-time-regex-matcher-using.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CEYBQH0ycCp7ImA9WhRVFEk.&quot;"><id>tag:blogger.com,1999:blog-13960885.post-3749620056258863875</id><published>2011-07-19T18:33:00.013-06:00</published><updated>2012-01-13T01:09:11.398-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-01-13T01:09:11.398-07:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="meta-programming constexpr performance" /><title>Want speed? Use constexpr meta-programming!</title><content type="html">It's official: C++11 has two meta-programming languages embedded in it! One is based on templates and other one using &lt;a href="http://en.wikipedia.org/wiki/C++0x#Generalized_constant_expressions"&gt;constexpr&lt;/a&gt;. Templates have been extensively used for meta-programming in C++03. C++11 now gives you one more option of writing compile-time meta-programs using &lt;strong&gt;constexpr&lt;/strong&gt;. The capabilities differ, however.  &lt;br /&gt;&lt;br /&gt;The meta-programming language that uses templates was discovered accidently and since then countless techniques have been developed. It is a pure functional language which allows you to manipulate compile-time integral literals and types but not floating point literals. Most people find the syntax of template meta-programming quite abominable because meta-functions must be implemented as structures and nested typedefs. Compile-time performance is also a pain point for this language feature.&lt;br /&gt;&lt;br /&gt;The &lt;a href="http://en.wikipedia.org/wiki/C++0x#Generalized_constant_expressions"&gt;generalized constant expressions&lt;/a&gt; (constexpr for short) feature allows C++11 compiler to peek into the implementation of a function (even classes) and perform optimizations if the function uses constants (literals) only. Constants can be integral, floating point, as well as string literals. The signature of constexpr functions is just like regular C++ functions but the body has several restrictions, such as only one return statement is allowed. Nevertheless, the syntax of constexpr functions is significantly friendlier than that of template-based meta-functions. Contrary to the design of templates, designers of generalized constant expressions are &lt;a href="http://www2.research.att.com/~bs/sac10-constexpr.pdf"&gt;well-aware&lt;/a&gt; of its meta-programming capabilities. &lt;br /&gt;&lt;br /&gt;In my view, the most interesting aspect of constexpr is its speed. constexpr functions can perform compile-time computations at lightening speed. To compare the performance I implemented an &lt;strong&gt;is_prime&lt;/strong&gt; algorithm in 3 different ways. Here is the algorithm in regular C++:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;&lt;br /&gt;static bool IsPrime(size_t number)&lt;br /&gt;{&lt;br /&gt;  if (number &lt;= 1)&lt;br /&gt;    return false;&lt;br /&gt;&lt;br /&gt;  for (size_t i = 2; i*i &lt;= number; ++i)&lt;br /&gt;    if (number % i == 0)&lt;br /&gt;      return false;&lt;br /&gt;&lt;br /&gt;  return true;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Here is the a template version of the same algorithm. Obviously, it is implemented as a collection of meta-functions in terms of structures.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;&lt;br /&gt;struct false_type &lt;br /&gt;{&lt;br /&gt;  typedef false_type type;&lt;br /&gt;  enum { value = 0 };&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;struct true_type &lt;br /&gt;{&lt;br /&gt;  typedef true_type type;&lt;br /&gt;  enum { value = 1 };&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;template&amp;lt;bool condition, class T, class U&amp;gt;&lt;br /&gt;struct if_&lt;br /&gt;{&lt;br /&gt;  typedef U type;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;template &amp;lt;class T, class U&amp;gt;&lt;br /&gt;struct if_&amp;lt;true, T, U&amp;gt;&lt;br /&gt;{&lt;br /&gt;  typedef T type;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;template&amp;lt;size_t N, size_t c&amp;gt; &lt;br /&gt;struct is_prime_impl&lt;br /&gt;{ &lt;br /&gt;  typedef typename if_&amp;lt;(c*c &amp;gt; N),&lt;br /&gt;                       true_type,&lt;br /&gt;                       typename if_&amp;lt;(N % c == 0),&lt;br /&gt;                                    false_type,&lt;br /&gt;                                    is_prime_impl&amp;lt;N, c+1&amp;gt; &amp;gt;::type &amp;gt;::type type;&lt;br /&gt;  enum { value = type::value };&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;template&amp;lt;size_t N&amp;gt; &lt;br /&gt;struct is_prime&lt;br /&gt;{&lt;br /&gt;  enum { value = is_prime_impl&amp;lt;N, 2&amp;gt;::type::value };&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;template &amp;lt;&amp;gt;&lt;br /&gt;struct is_prime&amp;lt;0&amp;gt;&lt;br /&gt;{&lt;br /&gt;  enum { value = 0 };&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;template &amp;lt;&amp;gt;&lt;br /&gt;struct is_prime&amp;lt;1&amp;gt;&lt;br /&gt;{&lt;br /&gt;  enum { value = 0 };&lt;br /&gt;};&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The above meta-program is a recursive implementation because that's how pure functional languages work. The &lt;strong&gt;is_prime_impl&lt;/strong&gt; meta-function does all the heavy lifting. To prevent infinite regression, lazy instantiation technique is used. All I can say at this point is you've to stare at the code to make sense out of it. &lt;br /&gt;&lt;br /&gt;And that's precisely the point: C++03 meta-programs are often unreadable and hard to comprehend. Not anymore! Here is the constexpr version of the same algorithm.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;&lt;br /&gt;constexpr bool is_prime_recursive(size_t number, size_t c)&lt;br /&gt;{&lt;br /&gt;  return (c*c &gt; number) ? true : &lt;br /&gt;           (number % c == 0) ? false : &lt;br /&gt;              is_prime_recursive(number, c+1);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;constexpr bool is_prime_func(size_t number)&lt;br /&gt;{&lt;br /&gt;  return (number &lt;= 1) ? false : is_prime_recursive(number, 2);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Well, I agree, although this version uses friendlier syntax, is not quite easy to read. Just like the previous one, it is recursive. I would say just get used to it! You can't live without recursion in C++ meta-programming world. Secondly, every function has a single return statement and the codifying logic for detecting primality requires abundant use of the ternary operator. &lt;br /&gt;&lt;br /&gt;As long as parameter &lt;strong&gt;number&lt;/strong&gt; is an integral constant, this constexpr version will compute the result at compile-time (C++11 compilers only). And when the number is a run-time integer, this same function is perfectly capable of computing the result at run-time. So you don't need two different versions of the same program: one for compile-time and another for run-time. One implementation does it all!&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;&lt;br /&gt;int main(void)&lt;br /&gt;{&lt;br /&gt;   static_assert(is_prime_func(7), "...");  // Computed at compile-time&lt;br /&gt;   int i = 11;&lt;br /&gt;   int j = is_prime_func(i)); // Computed at run-time&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Now that we have the implementations, lets talk performance. Take &lt;strong&gt;4256233&lt;/strong&gt;. This is 30,000th prime number! How long does the template version take to check if it is prime? It cannot! Yes, g++ 4.7 fails to compile &lt;strong&gt;is_prime&amp;lt;4256233&amp;gt;::value&lt;/strong&gt; because the computation exceeds the default (900) limit of the recursive template instantiations. So I used &lt;strong&gt;-ftemplate-depth-2100&lt;/strong&gt; allowing 2100 recursive instantiations! Does it work? Yes! How long does it take? About 1 second! That's not bad at all, you say. How fast is constexpr? About 0.154 seconds! &lt;br /&gt;&lt;br /&gt;Seems like templates are not too far behind. Wrong! How about fifth million prime number! It is 86028121. I could not get it to work with g++ 4.7. Somewhere in the range of 9300 recursive instantiations g++ seg-faults. That's brutal! isn't it? 9000+ recursive instantiations? There has to be a better way.&lt;br /&gt;&lt;br /&gt;So how long does the constexpr take for our fifth million prime number? 0.220 seconds! That's right! This large prime number makes almost no impact on constexpr compilation time. What could be the reason? There are no template instantiations. C++ compilers always did compile-time computations whenever it was possible. constexpr now allows &lt;strong&gt;user-defined abstractions&lt;/strong&gt; to hide those computations behind functions and yet allow compilers to see through them. &lt;br /&gt;By the way, I had to increase to depth of default allowed constexpr recursion using &lt;strong&gt;-fconstexpr-depth=9300&lt;/strong&gt;. The compiler bails out after this limit and resorts to run-time computation. Remember, the function is perfectly good for run-time computation as well (unlike templates version). &lt;br /&gt;&lt;br /&gt;I hope this little exercise will convince you that constexpr is the way to go for static meta-programming in C++ as long as you are dealing with literals (integral, floating point numbers, and strings). It is not clear whether constexpr functions are suitable for manipulating complex meta-programmable types, such as mpl::vector and related meta-functions, such as mpl::contains, mpl::push_back, and so on. If you are interested in playing with the above example more, here is the code: &lt;a href="http://cpptruths.googlecode.com/svn/trunk/cpp0x/is_prime.cpp"&gt;is_prime.cpp&lt;/a&gt; and &lt;a href="http://cpptruths.googlecode.com/svn/trunk/cpp0x/prime-test.sh"&gt;prime-test.sh&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/13960885-3749620056258863875?l=cpptruths.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CppTruths/~4/4alPk_kcUm0" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://cpptruths.blogspot.com/feeds/3749620056258863875/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=13960885&amp;postID=3749620056258863875" title="33 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/3749620056258863875?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/3749620056258863875?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CppTruths/~3/4alPk_kcUm0/want-speed-use-constexpr-meta.html" title="Want speed? Use constexpr meta-programming!" /><author><name>Sumant</name><uri>http://www.blogger.com/profile/11957855386259543653</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="28" height="32" src="http://4.bp.blogspot.com/--0WncXMeBPA/TchxRepk7bI/AAAAAAAABXo/oLNnYnw0K7A/s1600/Sumant-Tambe.JPG" /></author><thr:total>33</thr:total><feedburner:origLink>http://cpptruths.blogspot.com/2011/07/want-speed-use-constexpr-meta.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CkEDRH8zeyp7ImA9WhZUFkQ.&quot;"><id>tag:blogger.com,1999:blog-13960885.post-7125220373701254415</id><published>2011-06-10T00:58:00.005-06:00</published><updated>2011-06-10T01:24:35.183-06:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-06-10T01:24:35.183-06:00</app:edited><title>BoostCon'11 video on LEESA: Language for Embedded Query and Traversal</title><content type="html">&lt;a href="http://boostcon.boost.org"&gt;BoostCon'11&lt;/a&gt;, held in Aspen, Colorado, was a fantastic conference this year. Not only because I got a chance to present my work on &lt;a href="http://www.dre.vanderbilt.edu/LEESA/"&gt;LEESA&lt;/a&gt; but also because of the breadth and depth of the &lt;a href="http://boostcon.boost.org/2011-resources"&gt;topics covered&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;LEESA, as you may recall, is an embedded language in C++ to simplify XML programming. LEESA's programming model sits on top of the APIs generated by modern &lt;a href="http://www.artima.com/cppsource/xml_data_binding.html"&gt;XML data binding tools&lt;/a&gt;. LEESA gives you XPath-like syntax (wildcards, child-axis, descendant-axis, tuples) to simplify data extraction from an XML object model. &lt;br /&gt;&lt;br /&gt;I had a privilege to talk at length about LEESA in BoostCon'11. In the 1hr 41 minutes long video, I'm talking everything from why you need LEESA, how its implemented using cool C++ techniques, such as templates, meta-programming, compile-time and run-time performance, and what direction it may take in future. Here are the &lt;a href="https://github.com/boostcon/2011_presentations/raw/master/mon/leesa_boostcon.pdf"&gt;slides&lt;/a&gt; of the presentation.&lt;br /&gt;&lt;br /&gt;&lt;embed src="http://blip.tv/play/AYLA2XQC" type="application/x-shockwave-flash" width="480" height="390" wmode="transparent" allowscriptaccess="always" allowfullscreen="true" &gt;&lt;/embed&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/13960885-7125220373701254415?l=cpptruths.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CppTruths/~4/rIdd7W_msag" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://cpptruths.blogspot.com/feeds/7125220373701254415/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=13960885&amp;postID=7125220373701254415" title="4 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/7125220373701254415?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/7125220373701254415?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CppTruths/~3/rIdd7W_msag/boostcon11-video-on-leesa-language-for.html" title="BoostCon'11 video on LEESA: Language for Embedded Query and Traversal" /><author><name>Sumant</name><uri>http://www.blogger.com/profile/11957855386259543653</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="28" height="32" src="http://4.bp.blogspot.com/--0WncXMeBPA/TchxRepk7bI/AAAAAAAABXo/oLNnYnw0K7A/s1600/Sumant-Tambe.JPG" /></author><thr:total>4</thr:total><feedburner:origLink>http://cpptruths.blogspot.com/2011/06/boostcon11-video-on-leesa-language-for.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CEUNQXY8fyp7ImA9WhRVFEk.&quot;"><id>tag:blogger.com,1999:blog-13960885.post-956173591330588936</id><published>2010-04-05T18:17:00.006-06:00</published><updated>2012-01-13T01:11:30.877-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-01-13T01:11:30.877-07:00</app:edited><title>Generic Transpose using boost tuples</title><content type="html">Recently, while working on LEESA I faced an interesting problem of creating a transpose using generic programming. The problem is pretty straight forward. Suppose you are given a tuple of 2 vectors i.e. tuple&amp;lt;vector&amp;lt;int&amp;gt;, vector&amp;lt;long&amp;gt; &amp;gt;. Assuming both the vectors are of the same size, how would create a vector &amp;lt;tuple&amp;lt;int, long&amp;gt; &amp;gt; containing the data from the earlier two vectors? Of course, the size of the tuple may vary. &lt;br /&gt;&lt;br /&gt;Lets call the function transpose. A brute force solution would be to overload transpose function N times such that each one takes different size of tuple. Here's one that takes a three parameter tuple.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;&lt;br /&gt;template &amp;lt;class C1, class C2, class C3&amp;gt; // Assuming all Cs are STL containers&lt;br /&gt;std::vector&amp;lt;tuple&amp;lt;C1::value_type, C2::value_type, C3::value_type&amp;gt; &amp;gt;&lt;br /&gt;transpose (tuple&amp;lt;C1, C2, C3&amp;gt; const &amp;) { ... }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The implementation is fairly straight forward for those who have seen tuples in the past. We basically need a loop with three forward iterators that iterate over the source containers and populate a resultant tuple in each iteration. The resultant tuple is pushed into the vector that is returned at the end.&lt;br /&gt;&lt;br /&gt;However, implementing this in a more generic fashion is quite a lot of fun! A bit of metaprogramming and a byte of compile-time hierarchy generation gets the job done. Lets begin!&lt;br /&gt;&lt;br /&gt;First we need to extract out the value_types from the containers and create the type of the resultant tuple. Here is a small metaprogram that does half the job.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;&lt;br /&gt;template &amp;lt;&amp;gt;&lt;br /&gt;struct GetTransposeCons&amp;lt;tuples::null_type&amp;gt;&lt;br /&gt;{&lt;br /&gt;  typedef tuples::null_type type;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;template &amp;lt;class TupleOfVectors&amp;gt;&lt;br /&gt;struct GetTransposeCons&lt;br /&gt;{&lt;br /&gt;  typedef typename TupleOfVectors::head_type Head;&lt;br /&gt;  typedef typename TupleOfVectors::tail_type Tail;&lt;br /&gt;  typedef typename&lt;br /&gt;    tuples::cons&amp;lt;typename remove_reference&amp;lt;Head&amp;gt;::type::value_type,&lt;br /&gt;                 typename GetTransposeCons&amp;lt;Tail&amp;gt;::type&amp;gt; type;&lt;br /&gt;};&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Given a TupleOfVectors, it produces a cons-list, which is the underlying representation of boost tuples. remove_reference is not strictly needed here, but we'll see its use at the end. This metaprogram produces type cons&amp;lt;int, cons&amp;lt;float, cons&amp;lt;double, tuples::null_type&amp;gt; &amp;gt; &amp;gt; if we give tuple&amp;lt;vector&amp;lt;int&amp;gt;, vector&amp;lt;float&amp;gt;, vector&amp;lt;double&amp;gt; &amp;gt; as the input. The cons-list is practically as useful as the tuple itself. You can print it using tuple's I/O functionality, convert it into a regular tuple and so on so forth. &lt;br /&gt;&lt;br /&gt;But promise is a promise, we have to create a tuple! Lets write simple mapping from cons list to tuples. We create many(!) specializations of cons-list to do the mapping. &lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;&lt;br /&gt;template &amp;lt;class T&amp;gt;&lt;br /&gt;struct GetTransposeTuple;&lt;br /&gt;&lt;br /&gt;template &amp;lt;class T0&amp;gt;&lt;br /&gt;struct GetTransposeTuple&amp;lt;cons&amp;lt;T0, null_type&amp;gt; &amp;gt;&lt;br /&gt;{&lt;br /&gt;  typedef tuples::tuple&amp;lt;T0&amp;gt; type;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;template &amp;lt;class T0, class T1&amp;gt;&lt;br /&gt;struct GetTransposeTuple&amp;lt;cons&amp;lt;T0, cons&amp;lt;T1, null_type&amp;gt; &amp;gt; &amp;gt;&lt;br /&gt;{&lt;br /&gt;  typedef tuples::tuple&amp;lt;T0, T1&amp;gt; type;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;template &amp;lt;class T0, class T1, class T2&amp;gt;&lt;br /&gt;struct GetTransposeTuple&amp;lt;cons&amp;lt;T0, cons&amp;lt;T1, cons&amp;lt;T2, null_type&amp;gt; &amp;gt; &amp;gt; &amp;gt;&lt;br /&gt;{&lt;br /&gt;  typedef tuples::tuple&amp;lt;T0, T1, T2&amp;gt; type;&lt;br /&gt;};&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;I've not found a better way to do it. May be boost tuples have a simpler way to create an equivalent tuple type from cons-list like it does the other way round. tuple::inherited returns the underlying cons-list. Reverse mapping would be nice to have.&lt;br /&gt;&lt;br /&gt;With that now we can write a slightly complicated metafunction that converts a TupleOfVectors to a tuple of value_types. Here is how it looks.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;&lt;br /&gt;typedef typename GetTransposeTuple&amp;lt;&lt;br /&gt;  typename GetTransposeCons&amp;lt;TupleOfVectors&amp;gt;::type&lt;br /&gt;    &amp;gt;::type ValueTypeTuple;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Lets proceed with the hierarchy generation part. Hierarchy generation is quite idiomatic in C++ template metaprogramming while working on list of types as in tuples. Whenever there is a need to generate code that does something useful at run-time (not just compile-time) hierarchy generation comes quite handy. It is applicable when a single class can encapsulate the necessary run-time code for a single type in the cons-list (actually any other type-list for that matter). Rest is just the coordination of the generated classes. It's that simple!&lt;br /&gt;&lt;br /&gt;In the case of generic transpose, there needs to be a class for each type in the tuple. Each class does the following things.&lt;br /&gt;&lt;br /&gt;1. Hold a reference to the source vector.&lt;br /&gt;2. Hold an iterator to that vector.&lt;br /&gt;3. Extract the value iterator is pointing to and advance the iterator.&lt;br /&gt;4. Copy the value into the &amp;lt;span style="font-weight:bold;"&amp;gt;right&amp;lt;/span&amp;gt; position in the resultant tuple.&lt;br /&gt;&lt;br /&gt;Finally, the resultant tuple is pushed in the resultant vector, which is returned when all the iterators reach the end.&lt;br /&gt;&lt;br /&gt;The gist of hierarchy generation is in its inheritance expression.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;&lt;br /&gt;template &amp;lt;class TupleOfVectors,&lt;br /&gt;          class ValueTypeTuple = /* we saw earlier */,&lt;br /&gt;          unsigned int TUPLE_INDEX = 0&amp;gt;&lt;br /&gt;struct Transposer&lt;br /&gt;  : Transposer &amp;lt;typename TupleOfVectors::tail_type,&lt;br /&gt;                ValueTypeTuple,&lt;br /&gt;                TUPLE_INDEX + 1&amp;gt;&lt;br /&gt;{ ... };&lt;br /&gt;&lt;br /&gt;template &amp;lt;class ValueTypeTuple,&lt;br /&gt;          unsigned int INDEX&amp;gt;&lt;br /&gt;struct Transposer &amp;lt;tuples::null_type, ValueTypeTuple, INDEX&amp;gt;&lt;br /&gt;{ ... };&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Transposer inherits from another instantiation of itself. The first and the third template parameters change progressively. The recursion ends only when the TupleOfVectors is exhausted and that's when the null_type specialization of the Transposer comes into picture. Note that the ValueTypeTuple remains unchanged throughout the hierarchy but the INDEX into that ValueTypeTuple increases. That is, if the derived Transposer copies the value in slot #i then its immediate base Transposer copies the value in slot #i+1. We don't care what the slot number is for the Transposer of null_type specialization.&lt;br /&gt;&lt;br /&gt;Lets now write the body of the Transposer. Here are some typedef that come handy in the implementation of the Transposer template.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;&lt;br /&gt;  typedef typename TupleOfVectors::head_type Head;&lt;br /&gt;  typedef typename TupleOfVectors::tail_type Tail;&lt;br /&gt;  typedef typename remove_reference&amp;lt;Head&amp;gt;::type HeadContainer;&lt;br /&gt;  typedef Transposer&amp;lt;Tail, ValueTypeTuple, TUPLE_INDEX + 1&amp;gt; super;&lt;br /&gt;  typedef ValueTypeTuple TransposeTuple;&lt;br /&gt;  typedef std::vector&amp;lt;ValueTypeTuple&amp;gt; Transpose;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The class template has two private members.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;&lt;br /&gt;  HeadContainer const &amp; head_container_;&lt;br /&gt;  typename HeadContainer::const_iterator head_iter_;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Note that the HeadContainer is gonna be different in every instantiation of the Transposer. The constructor looks like this&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;&lt;br /&gt;  Transposer(TupleOfVectors const &amp; tuple)&lt;br /&gt;    : super(tuple.get_tail()),&lt;br /&gt;      head_container_(tuple.get_head()),&lt;br /&gt;      head_iter_(head_container_.begin())&lt;br /&gt;  {}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Each constructor takes what it needs from the TupleOfVectors and passes the rest of it to its base class. Tuple expects such use and provides the right API (get_head, get_tail) to achieve that. The reference to the container is assigned to the head_container_ member and the iterator is also initialized.  The same happens in all the constructors except the last one that is a specialization of null_type. Its constructor is no-op. &lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;&lt;br /&gt;template &amp;lt;class ValueTypeTuple,&lt;br /&gt;          unsigned int INDEX&amp;gt;&lt;br /&gt;struct Transposer &amp;lt;tuples::null_type, ValueTypeTuple, INDEX&amp;gt;&lt;br /&gt;{&lt;br /&gt;protected:&lt;br /&gt;  void populate_tuple(ValueTypeTuple &amp;) {}&lt;br /&gt;  Transposer (tuples::null_type const &amp;) {}&lt;br /&gt;};&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;With this much setup, everything that is needed to begin transpose procedure is arranged neat and tidy. Now we write the final get_transpose method that creates the transpose. &lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;&lt;br /&gt;  Transpose get_transpose ()&lt;br /&gt;  {&lt;br /&gt;    Transpose tran;&lt;br /&gt;    tran.reserve(head_container_.size());&lt;br /&gt;    for(typename HeadContainer::const_iterator iter = head_container_.begin();&lt;br /&gt;        iter != head_container_.end();&lt;br /&gt;        ++iter)&lt;br /&gt;    {&lt;br /&gt;      ValueTypeTuple vtuple;&lt;br /&gt;      this-&amp;gt;populate_tuple(vtuple);&lt;br /&gt;      tran.push_back(vtuple);&lt;br /&gt;    }&lt;br /&gt;    return tran;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;protected:&lt;br /&gt;&lt;br /&gt;  void populate_tuple(ValueTypeTuple &amp; vtuple)&lt;br /&gt;  {&lt;br /&gt;    if(head_iter_ == head_container_.end())&lt;br /&gt;      throw std::runtime_error("Container bound exceeded.");&lt;br /&gt;    else&lt;br /&gt;    {&lt;br /&gt;      vtuple.get&amp;lt;TUPLE_INDEX&amp;gt;() = *head_iter_++;&lt;br /&gt;      super::populate_tuple (vtuple);&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;get_transpose method has a loop that iterates over all the elements of the head_container. For each iteration, it creates a default initialized ValueTypeTuple, which needs to be populated with one sample from each of the source containers. We do that in the populate_tuple method, which receives the tuple as a non-const reference. It does #3 and #4 bullets mentioned earlier. It extracts one data sample from the container using the iterator, advances the iterator, and then copies that data sample into the "right place" in the tuple. The "right place" is nothing but the INDEX parameter that was passed while creating the hierarchy. Once again, tuple provided the right API to assign the Nth entry in a tuple provided N is known at compile-time. Finally, the same procedure has to happen in every class in the hierarchy. We simply call the base class's populate_tuple function and pass the partially populated ValueTypeTuple by reference. Note that populate_tuple throws runtime_error exception if some iterator hits end of the container in the middle of transpose procedure. &lt;br /&gt;&lt;br /&gt;Finally, we implement the transpose function in terms of Transposer template.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;&lt;br /&gt;template &amp;lt;class TupleOfVectors&amp;gt;&lt;br /&gt;typename Transposer&amp;lt;TupleOfVectors&amp;gt;::Transpose&lt;br /&gt;transpose (TupleOfVectors const &amp; tupleofv)&lt;br /&gt;{&lt;br /&gt;  return Transposer&amp;lt;TupleOfVectors&amp;gt;(tupleofv).get_transpose();&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Here is how we use it.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;&lt;br /&gt;  int arr[5] = {10, 20, 30, 40, 50};&lt;br /&gt;  std::vector&amp;lt;int&amp;gt; vint(arr, arr+5);&lt;br /&gt;  std::list&amp;lt;float&amp;gt; lfloat(arr, arr+5);&lt;br /&gt;  std::vector&amp;lt;long&amp;gt; vlong(arr, arr+5);&lt;br /&gt;&lt;br /&gt;  Transposer&amp;lt;TupleOfV&amp;gt;::Transpose tran &lt;br /&gt;    = transpose(make_tuple(cref(vint), cref(lfloat), cref(vlong)));&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;To avoid unnecessary copies of the source vectors, we make use of cref reference_wrapper. In such cases, each entry is a const-reference to the original container, which causes problems in the GetTransposeCons metafunction if we don't use remove_reference. &lt;br /&gt;&lt;br /&gt;The complete source code is available &lt;a href="http://cpptruths.googlecode.com/svn/trunk/cpp/Transposer.cpp"&gt;here&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/13960885-956173591330588936?l=cpptruths.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CppTruths/~4/oZaYgTBCrvI" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://cpptruths.blogspot.com/feeds/956173591330588936/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=13960885&amp;postID=956173591330588936" title="9 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/956173591330588936?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/956173591330588936?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CppTruths/~3/oZaYgTBCrvI/generic-transpose-using-boost-tuples.html" title="Generic Transpose using boost tuples" /><author><name>Sumant</name><uri>http://www.blogger.com/profile/11957855386259543653</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="28" height="32" src="http://4.bp.blogspot.com/--0WncXMeBPA/TchxRepk7bI/AAAAAAAABXo/oLNnYnw0K7A/s1600/Sumant-Tambe.JPG" /></author><thr:total>9</thr:total><feedburner:origLink>http://cpptruths.blogspot.com/2010/04/generic-transpose-using-boost-tuples.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CEMGSHw4eyp7ImA9WhRVFEk.&quot;"><id>tag:blogger.com,1999:blog-13960885.post-2360486061646887342</id><published>2010-03-03T20:54:00.021-07:00</published><updated>2012-01-13T01:13:49.233-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-01-13T01:13:49.233-07:00</app:edited><title>Faster meta-programs using gcc 4.5 and C++0x</title><content type="html">One of the practical issues with C++ meta-programming is its speed. C++ programs that use heavy meta-programming can be notoriously slow to compile on contemporary compilers. Things are changing, however. Check the following comparison of gcc 4.5 against gcc 4.4.3. &lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/_x2WPvH4cnWQ/S4831CbASFI/AAAAAAAABF0/7tV2kNf4kXg/s1600-h/gcc45-compilation.png"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 350px; height: 400px;" src="http://2.bp.blogspot.com/_x2WPvH4cnWQ/S4831CbASFI/AAAAAAAABF0/7tV2kNf4kXg/s400/gcc45-compilation.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5444631858836949074" /&gt;&lt;/a&gt;&lt;br /&gt;The first graph is obtained from a program that creates a binary tree of template instantiations. The x-axis shows the number of instantiations when value of N goes from 8 to 17. I could not build up patience for gcc 4.4.3 beyond 16363 instantiations (N=13). On the other hand, gcc 4.5 does pretty good and its increase in compilation time is indeed linear as mentioned &lt;a href="http://gcc.gnu.org/gcc-4.5/changes.html"&gt;here&lt;/a&gt;. Here is the program that creates a binary tree of template instantiations.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;&lt;br /&gt;template &lt;int Depth, int A, typename B&gt;&lt;br /&gt;struct Binary &lt;br /&gt;{&lt;br /&gt;  enum { value = 1 +&lt;br /&gt;         Binary&lt;Depth-1, 0, Binary&gt;::value +&lt;br /&gt;         Binary&lt;Depth-1, 1, Binary&gt;::value };&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;template&lt;int A, typename B&gt;&lt;br /&gt;struct Binary&lt;0, A, B&gt; &lt;br /&gt;{&lt;br /&gt;  enum { value = 1 };&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;int main(void) &lt;br /&gt;{&lt;br /&gt;  static const int N = 10;&lt;br /&gt;  const int instantiations = Binary&lt;N,0,int&gt;::value;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The second graph is obtained from a program that finds an intersection of two &lt;a href="http://www.boost.org/doc/libs/1_42_0/libs/mpl/doc/index.html"&gt;MPL&lt;/a&gt; vectors. Again gcc 4.5 shows linear increase in compilation time as opposed to gcc 4.4.3. Here is the intersection program.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;&lt;br /&gt;template &amp;lt;class V1, class V2&amp;gt;&lt;br /&gt;struct Intersection &lt;br /&gt;{&lt;br /&gt;  typedef typename&lt;br /&gt;     boost::mpl::copy_if&amp;lt;V1,&lt;br /&gt;     boost::mpl::contains&amp;lt;V2, boost::mpl::placeholders::_1&amp;gt; &amp;gt;::type type;&lt;br /&gt;};&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;While all that is already exciting, it fades in comparison to the performance of &lt;a href="http://en.wikipedia.org/wiki/C%2B%2B0x#Variadic_templates"&gt;variadic templates&lt;/a&gt; in C++0x. The green line in the second graph shows negligible effect on performance with the increasing number of template parameters. Here is my intersection metaprogram using variadic templates.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: cpp"&gt;&lt;br /&gt;struct null_type {};&lt;br /&gt;template &amp;lt;typename... Arg&amp;gt; struct vector {};&lt;br /&gt;&lt;br /&gt;template &amp;lt;typename V&amp;gt; struct front;&lt;br /&gt;template &amp;lt;typename V&amp;gt; struct pop_front;&lt;br /&gt;&lt;br /&gt;template &amp;lt;typename Head, typename... Tail&amp;gt;&lt;br /&gt;struct front &amp;lt;vector &amp;lt;Head, Tail...&amp;gt; &amp;gt; &lt;br /&gt;{&lt;br /&gt;  typedef Head type;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;template &amp;lt;&amp;gt;&lt;br /&gt;struct front &amp;lt;vector &amp;lt;&amp;gt; &amp;gt; &lt;br /&gt;{&lt;br /&gt;  typedef null_type type;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;template &amp;lt;typename Head, typename... Tail&amp;gt;&lt;br /&gt;struct pop_front &amp;lt;vector &amp;lt;Head, Tail...&amp;gt; &amp;gt; &lt;br /&gt;{&lt;br /&gt;  typedef vector&amp;lt;Tail...&amp;gt; type;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;template &amp;lt;&amp;gt;&lt;br /&gt;struct pop_front &amp;lt;vector &amp;lt;&amp;gt; &amp;gt; &lt;br /&gt;{&lt;br /&gt;  typedef vector&amp;lt;&amp;gt; type;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;template &amp;lt;typename Vector, typename T&amp;gt; struct push_back;&lt;br /&gt;&lt;br /&gt;template &amp;lt;typename T, typename... Args&amp;gt;&lt;br /&gt;struct push_back &amp;lt; vector&amp;lt;Args...&amp;gt;, T&amp;gt; &lt;br /&gt;{&lt;br /&gt;  typedef vector&amp;lt;Args..., T&amp;gt; type;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;template &amp;lt;typename Vector&amp;gt; struct size;&lt;br /&gt;&lt;br /&gt;template &amp;lt;typename... Args&amp;gt;&lt;br /&gt;struct size &amp;lt;vector &amp;lt;Args...&amp;gt; &amp;gt; &lt;br /&gt;{&lt;br /&gt;  typedef size type;&lt;br /&gt;  enum { value = sizeof...(Args) };&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;template &amp;lt;typename Vector, typename What&amp;gt; struct contains;&lt;br /&gt;&lt;br /&gt;template &amp;lt;typename What, typename Head, typename... Tail&amp;gt;&lt;br /&gt;struct contains &amp;lt; vector&amp;lt;Head, Tail...&amp;gt;, What&amp;gt; : &lt;br /&gt;  std::conditional &amp;lt; std::is_same&amp;lt;Head, What&amp;gt;::value,&lt;br /&gt;                     std::true_type,&lt;br /&gt;                     contains &amp;lt; vector&amp;lt;Tail...&amp;gt;, What&amp;gt; &amp;gt;::type&lt;br /&gt;{&lt;br /&gt;  typedef contains type;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;template &amp;lt;typename What&amp;gt;&lt;br /&gt;struct contains &amp;lt;vector&amp;lt;&amp;gt;, What&amp;gt; &lt;br /&gt;{&lt;br /&gt;  typedef contains type;&lt;br /&gt;  enum { value = 0 };&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;template &amp;lt;class V1, class V2&amp;gt;&lt;br /&gt;struct Intersection;&lt;br /&gt;&lt;br /&gt;template &amp;lt;class V1, class V2, unsigned int N&amp;gt;&lt;br /&gt;struct Intersection_impl&lt;br /&gt;{&lt;br /&gt;  typedef typename front&amp;lt;V2&amp;gt;::type Head;&lt;br /&gt;  typedef typename pop_front&amp;lt;V2&amp;gt;::type Tail;&lt;br /&gt;  typedef typename Intersection&amp;lt;V1, Tail&amp;gt;::type I;&lt;br /&gt;&lt;br /&gt;  typedef typename &lt;br /&gt;    std::conditional&amp;lt;contains&amp;lt;V1, Head&amp;gt;::value,&lt;br /&gt;                     typename push_back&amp;lt;I, Head&amp;gt;::type,&lt;br /&gt;                     I &amp;gt;::type type;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;template &amp;lt;class V1, class V2&amp;gt;&lt;br /&gt;struct Intersection_impl &amp;lt;V1, V2, 0&amp;gt; &lt;br /&gt;{&lt;br /&gt;  typedef vector&amp;lt;&amp;gt; type;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;template &amp;lt;class V1, class V2&amp;gt;&lt;br /&gt;struct Intersection &lt;br /&gt;{&lt;br /&gt;  typedef typename Intersection_impl&amp;lt;V1, V2, &lt;br /&gt;          size&amp;lt;V1&amp;gt;::value * size&amp;lt;V2&amp;gt;::value&amp;gt;::type type;&lt;br /&gt;};&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;So long story short, seems like better days are ahead for C++ meta-programming!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/13960885-2360486061646887342?l=cpptruths.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CppTruths/~4/vDh5Vt1olO8" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://cpptruths.blogspot.com/feeds/2360486061646887342/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=13960885&amp;postID=2360486061646887342" title="29 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/2360486061646887342?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/2360486061646887342?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CppTruths/~3/vDh5Vt1olO8/faster-meta-programs-using-gcc-45-and.html" title="Faster meta-programs using gcc 4.5 and C++0x" /><author><name>Sumant</name><uri>http://www.blogger.com/profile/11957855386259543653</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="28" height="32" src="http://4.bp.blogspot.com/--0WncXMeBPA/TchxRepk7bI/AAAAAAAABXo/oLNnYnw0K7A/s1600/Sumant-Tambe.JPG" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://2.bp.blogspot.com/_x2WPvH4cnWQ/S4831CbASFI/AAAAAAAABF0/7tV2kNf4kXg/s72-c/gcc45-compilation.png" height="72" width="72" /><thr:total>29</thr:total><feedburner:origLink>http://cpptruths.blogspot.com/2010/03/faster-meta-programs-using-gcc-45-and.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CU8GSHc8eSp7ImA9WxNXFE4.&quot;"><id>tag:blogger.com,1999:blog-13960885.post-7446176951823640127</id><published>2009-08-11T22:39:00.005-06:00</published><updated>2009-10-01T15:50:29.971-06:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-10-01T15:50:29.971-06:00</app:edited><title>Modifying temporaries</title><content type="html">Temporary objects are created and destroyed all the time in a C++ program. A simple example would be a function that returns by value. A temporary is as good as a const object because it makes little sense (usually) to change a temporary object, which is unnamed and has a very short time span. (Note: A temporary can be bound to a const reference in which case the scope of the temporary is the same as that of the reference.) However, as it turns out, in C++ you can change temporaries ... if they are of class type! You can call non-const member functions on a temporary. This is quite similar to binding a temporary to a non-const reference and changing it. Section 3.10.10 in C++ ISO/IEC 14882:1998 standard clearly mentions this exception. There are at least two practical use of such an exception. One is the "&lt;a href="http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Named_Parameter"&gt;Named Parameter&lt;/a&gt;" idiom and the other one is the &lt;a href="http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Move_Constructor"&gt;Move Constructor idiom&lt;/a&gt;. In case of the named parameter idiom, the member functions might prefer to return the object by non-const reference instead of a by value. Here is an example:&lt;br /&gt;&lt;br /&gt;class X&lt;br /&gt;{&lt;br /&gt;  public:&lt;br /&gt;    int a;&lt;br /&gt;    char b;&lt;br /&gt;    X() : a(0), b(0) {}&lt;br /&gt;    X setA(int i)  { a = i; return *this; } // non-const function&lt;br /&gt;    X setB(char c) { b = c; return *this; } // non-const function&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;std::ostream &amp; operator &lt;&lt; (std::ostream &amp; o, X const &amp; x)&lt;br /&gt;{&lt;br /&gt;  o &amp;lt;&amp;lt; x.a &amp;lt;&amp;lt; " " &amp;lt;&amp;lt; x.b;&lt;br /&gt;  return o;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;X createX() // returns X by value.&lt;br /&gt;{ &lt;br /&gt;  return X(); &lt;br /&gt;} &lt;br /&gt;&lt;br /&gt;int main (void)&lt;br /&gt;{&lt;br /&gt;  // The following code uses the named parameter idiom.&lt;br /&gt;  std::cout &amp;lt;&amp;lt; createX().setA(10).setB('Z') &amp;lt;&amp;lt; std::endl; &lt;br /&gt;}&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/13960885-7446176951823640127?l=cpptruths.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CppTruths/~4/qgG0k5ittLU" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://cpptruths.blogspot.com/feeds/7446176951823640127/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=13960885&amp;postID=7446176951823640127" title="13 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/7446176951823640127?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/7446176951823640127?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CppTruths/~3/qgG0k5ittLU/modifying-temporaries.html" title="Modifying temporaries" /><author><name>Sumant</name><uri>http://www.blogger.com/profile/11957855386259543653</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="28" height="32" src="http://4.bp.blogspot.com/--0WncXMeBPA/TchxRepk7bI/AAAAAAAABXo/oLNnYnw0K7A/s1600/Sumant-Tambe.JPG" /></author><thr:total>13</thr:total><feedburner:origLink>http://cpptruths.blogspot.com/2009/08/modifying-temporaries.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DEMMQXk-eip7ImA9WxFWF0k.&quot;"><id>tag:blogger.com,1999:blog-13960885.post-3793860423765868894</id><published>2009-03-21T13:43:00.015-06:00</published><updated>2010-06-05T08:01:20.752-06:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-06-05T08:01:20.752-06:00</app:edited><title>LEESA: A new way of typed XML programming in C++</title><content type="html">Some of my recent research work has focused on developing a highly generic and reusable library for complex object structure traversal, which is best exemplified by schema driven XML programming. I'm glad to present a research paper called &lt;a href="http://www.dre.vanderbilt.edu/~sutambe/documents/pubs/LEESA-DSL09.pdf"&gt;LEESA: Embedding Strategic and XPath-like Object Structure Traversals in C++&lt;/a&gt;, which will be published in the proceedings of &lt;a href="http://www.smart-generators.org/DSLWC"&gt;IFIP Working Conference on Domain Specific Languages (DSL WC)&lt;/a&gt;, 2009 at Oxford, UK. &lt;a href="http://www.dre.vanderbilt.edu/LEESA"&gt;LEESA&lt;/a&gt; stands for &lt;span style="font-weight:bold;"&gt;L&lt;/span&gt;anguage for &lt;span style="font-weight:bold;"&gt;E&lt;/span&gt;mbedded qu&lt;span style="font-weight:bold;"&gt;E&lt;/span&gt;ry and traver&lt;span style="font-weight:bold;"&gt;SA&lt;/span&gt;l. LEESA has advanced the state-of-the-art of the &lt;a href="http://blogs.msdn.com/xmlteam/archive/2006/11/27/typed-xml-programmer-welcome-to-linq.aspx"&gt;typed XML programming&lt;/a&gt; in standard C++ to a level where many benefits of static type analysis can be maintained while enjoying a succinct syntax similar to that of XPath. Below, a quick motivating example of LEESA that sorts and prints the names of the authors in a XML book catalog is shown.&lt;br /&gt;&lt;br /&gt;Catalog() &gt;&gt; Book() &gt;&gt; Author() &gt;&gt; Sort(Author(), LastNameComparator) &gt;&gt; ForEach(Author(), print);&lt;br /&gt;&lt;br /&gt;The key thing to be noted here is that it is not a string encoded query. In fact, the C++ compiler checks the compatibility of this expression against the book catalog XML schema at &lt;span style="font-weight:bold;"&gt;compile-time&lt;/span&gt;! LEESA uses &lt;a href="http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Expression-template"&gt;Expression templates&lt;/a&gt; idiom to achieve this highly intuitive, XPath-like syntax. Overall, LEESA's implementation is an exciting combination of generic programming, operator overloading, expression templates, C++ metaprogramming, Boost MPL, C++0x Concepts, and heck a lot of template hackery to make all the things work together! Interesting details are presented in the paper mentioned above. &lt;br /&gt;&lt;br /&gt;The &lt;a href="http://www.dre.vanderbilt.edu/~sutambe/ccount/click.php?id=1"&gt;source code&lt;/a&gt; of LEESA is available. However, LEESA's current implementation is based on &lt;a href="http://www.isis.vanderbilt.edu/tools/UDM"&gt;Universal Data Model (UDM 3.2.1)&lt;/a&gt; -- a full-fledged code generator for model-driven development that can be used as a XML schema compiler. Other code generators could be used provided they are extended to produce the necessary layers of abstraction described in the paper.&lt;br /&gt;&lt;br /&gt;In the upcoming posts, I plan to document some of my experiences of developing LEESA.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/13960885-3793860423765868894?l=cpptruths.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CppTruths/~4/xh2UAYbZ5bw" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://cpptruths.blogspot.com/feeds/3793860423765868894/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=13960885&amp;postID=3793860423765868894" title="14 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/3793860423765868894?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/3793860423765868894?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CppTruths/~3/xh2UAYbZ5bw/leesa-new-way-of-xml-programming-in-c.html" title="LEESA: A new way of typed XML programming in C++" /><author><name>Sumant</name><uri>http://www.blogger.com/profile/11957855386259543653</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="28" height="32" src="http://4.bp.blogspot.com/--0WncXMeBPA/TchxRepk7bI/AAAAAAAABXo/oLNnYnw0K7A/s1600/Sumant-Tambe.JPG" /></author><thr:total>14</thr:total><feedburner:origLink>http://cpptruths.blogspot.com/2009/03/leesa-new-way-of-xml-programming-in-c.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DUAGQXs6fCp7ImA9WxRRE0s.&quot;"><id>tag:blogger.com,1999:blog-13960885.post-4363525348886741572</id><published>2008-09-21T14:57:00.005-06:00</published><updated>2008-09-25T12:35:20.514-06:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-09-25T12:35:20.514-06:00</app:edited><title>Int-to-type idiom and infinite regress</title><content type="html">A new writeup on &lt;a href="http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Int-To-Type"&gt;Int-to-type idiom&lt;/a&gt; has been posted on More C++ Idioms wikibook. It is used to achieve static dispatching based on constant integral values. I'll finish the writeup of the idiom here with special attention to how int-to-type idiom can lead to infinite series of type instantiations and why. The idiomatic form of the Int-to-type idiom is given below.&lt;br /&gt;&lt;br /&gt;template &amp;lt;int I&amp;gt;&lt;br /&gt;struct Int2Type&lt;br /&gt;{&lt;br /&gt;  enum { value = I };&lt;br /&gt;  typedef Int2Type&amp;lt;I&amp;gt; type;&lt;br /&gt;  typedef Int2Type&amp;lt;I+1&amp;gt; next;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;The &lt;span style="font-style:italic;"&gt;type&lt;/span&gt; typedef defined inside the template is the type itself. I.e, &lt;span style="font-style:italic;"&gt;Int2Type&lt;10&gt;::type&lt;/span&gt; is same as &lt;span style="font-style:italic;"&gt;Int2Type&lt;10&gt;&lt;/span&gt;. The &lt;span style="font-style:italic;"&gt;next&lt;/span&gt; typedef gives the following type in order. However, compiler is not required to instantiate the next type unless and until two things happen: (1) an instance of the type is created or (2) an associated type is accessed at compile-time. For example, Int2Type&lt;10&gt; will be instantiated if one the following two things are written.&lt;br /&gt;&lt;br /&gt;Int2Type&amp;lt;10&amp;gt; a;  // a variable declaration.&lt;br /&gt;typedef Int2Type&amp;lt;10&amp;gt::type INT10; // accessing an associated type.&lt;br /&gt;&lt;br /&gt;For kicks, lets see what happens if we add "::type" in the typedef of next. &lt;br /&gt;&lt;br /&gt;template &amp;lt;int I&amp;gt;&lt;br /&gt;struct Int2Type&lt;br /&gt;{&lt;br /&gt;  enum { value = I };&lt;br /&gt;  typedef Int2Type&amp;lt;I&amp;gt; type;&lt;br /&gt;  typedef typename Int2Type&amp;lt;I+1&amp;gt;::type next;  // Note change here.&lt;br /&gt;};&lt;br /&gt;int main (void)&lt;br /&gt;{&lt;br /&gt;  Int2Type&lt;10&gt; i; // This instantiation will trigger an infinite chain.&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;For each instantiation of the Int2Type template, its "next" type is also instantiated because we are accessing the associated type defined inside the template. This leads to an infinite series of instantiations of the template with no end. Obviously, C++ compiler stops after predefined number of recursive instantiations with an error message. More formally, this problem is also known as &lt;span style="font-weight:bold;"&gt;infinite regress&lt;/span&gt; where the original problem reappears in the solution to the problem.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/13960885-4363525348886741572?l=cpptruths.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CppTruths/~4/-C0rooRYAFM" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://cpptruths.blogspot.com/feeds/4363525348886741572/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=13960885&amp;postID=4363525348886741572" title="21 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/4363525348886741572?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/4363525348886741572?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CppTruths/~3/-C0rooRYAFM/int-to-type-idiom-and-infinite-regress.html" title="Int-to-type idiom and infinite regress" /><author><name>Sumant</name><uri>http://www.blogger.com/profile/11957855386259543653</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="28" height="32" src="http://4.bp.blogspot.com/--0WncXMeBPA/TchxRepk7bI/AAAAAAAABXo/oLNnYnw0K7A/s1600/Sumant-Tambe.JPG" /></author><thr:total>21</thr:total><feedburner:origLink>http://cpptruths.blogspot.com/2008/09/int-to-type-idiom-and-infinite-regress.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DkAFSXY_cSp7ImA9WxRSFk8.&quot;"><id>tag:blogger.com,1999:blog-13960885.post-2914737952492509092</id><published>2008-09-16T21:50:00.002-06:00</published><updated>2008-09-16T22:11:58.849-06:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-09-16T22:11:58.849-06:00</app:edited><title>copy elision and copy-and-swap idiom</title><content type="html">An updated writeup of the &lt;a href="http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Copy-and-swap"&gt;copy-and-swap idiom&lt;/a&gt; is now available on the &lt;a href="http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms"&gt;More C++ Idioms&lt;/a&gt; wikibook. A comparison of two different styles of assignment operator is shown. First version accepts the parameter as &lt;span style="font-style:italic;"&gt;pass-by-const-reference&lt;/span&gt; whereas the second version accepts it as &lt;span style="font-style:italic;"&gt;pass-by-value&lt;/span&gt;. For some classes &lt;span style="font-style:italic;"&gt;pass-by-value&lt;/span&gt; turns out to be more efficient as a copy of the object is elided when the right hand side is a rvalue.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/13960885-2914737952492509092?l=cpptruths.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CppTruths/~4/a_OD0BVQqNU" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://cpptruths.blogspot.com/feeds/2914737952492509092/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=13960885&amp;postID=2914737952492509092" title="11 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/2914737952492509092?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/2914737952492509092?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CppTruths/~3/a_OD0BVQqNU/copy-elision-and-copy-and-swap-idiom.html" title="copy elision and copy-and-swap idiom" /><author><name>Sumant</name><uri>http://www.blogger.com/profile/11957855386259543653</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="28" height="32" src="http://4.bp.blogspot.com/--0WncXMeBPA/TchxRepk7bI/AAAAAAAABXo/oLNnYnw0K7A/s1600/Sumant-Tambe.JPG" /></author><thr:total>11</thr:total><feedburner:origLink>http://cpptruths.blogspot.com/2008/09/copy-elision-and-copy-and-swap-idiom.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CUYAQH4yfip7ImA9WxRTEkk.&quot;"><id>tag:blogger.com,1999:blog-13960885.post-4920966696870643491</id><published>2008-08-31T21:36:00.003-06:00</published><updated>2008-08-31T22:25:41.096-06:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-08-31T22:25:41.096-06:00</app:edited><title>linked list using std::pair (infinite regression)</title><content type="html">Defining a node of a linked-list using std::pair sounds as simple as drinking a Starbucks's white chocolate mocha. But it really isn't. Give it a try! The constraint is to use std::pair's first or second as a pointer to the structure itself, like in any linked-list's node. As far as I know, it is impossible unless you resort to ugly casts from void pointers. The problem is actually quite well known and gives rise to something known as &lt;a href="http://en.wikipedia.org/wiki/Infinite_regress"&gt;infinite regress&lt;/a&gt;, where the problem you want to solve reappears in the solution to the problem. &lt;br /&gt;&lt;br /&gt;typedef std::pair&amp;lt;int, /* Pointer to this pair!! */ &amp;gt; Node;&lt;br /&gt;&lt;br /&gt;The closest thing I could come up with is something like the one below.&lt;br /&gt;&lt;br /&gt;struct Node : std::pair &amp;lt;int, Node *&amp;gt;&lt;br /&gt;{};&lt;br /&gt;&lt;br /&gt;Node n;&lt;br /&gt;n.second = &amp;n;  // A cyclic linked-list.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/13960885-4920966696870643491?l=cpptruths.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CppTruths/~4/US1OS4IOZp0" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://cpptruths.blogspot.com/feeds/4920966696870643491/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=13960885&amp;postID=4920966696870643491" title="5 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/4920966696870643491?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/4920966696870643491?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CppTruths/~3/US1OS4IOZp0/linked-list-using-stdpair-infinite.html" title="linked list using std::pair (infinite regression)" /><author><name>Sumant</name><uri>http://www.blogger.com/profile/11957855386259543653</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="28" height="32" src="http://4.bp.blogspot.com/--0WncXMeBPA/TchxRepk7bI/AAAAAAAABXo/oLNnYnw0K7A/s1600/Sumant-Tambe.JPG" /></author><thr:total>5</thr:total><feedburner:origLink>http://cpptruths.blogspot.com/2008/08/linked-list-using-stdpair-infinite.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DkABQHc8fip7ImA9WxdWFk8.&quot;"><id>tag:blogger.com,1999:blog-13960885.post-2451788015292327094</id><published>2008-07-09T10:52:00.002-06:00</published><updated>2008-07-09T11:32:31.976-06:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-07-09T11:32:31.976-06:00</app:edited><title>return void</title><content type="html">I thought it would be interesting to discuss a subtle C/C++ interview question I learned recently. Question is deceptively simple: "Can you write a return statement in a function that returns void?" The answer is "Yes! You can return void!" The following program seems to be a valid C/C++ program. &lt;br /&gt;&lt;br /&gt;static void foo (void) { }&lt;br /&gt;static void bar (void) {&lt;br /&gt;  return foo(); // Note this return statement.&lt;br /&gt;}&lt;br /&gt;int main (void) {&lt;br /&gt;  bar();&lt;br /&gt;  return 0;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;I tested it using gcc4 and VS9. With -ansi and -pedantic compiler options for gcc, it throws just a warning pointing at line #5.&lt;br /&gt;&lt;br /&gt;return_void.c:5: warning: return with a value, in function returning void&lt;br /&gt;&lt;br /&gt;Although use of such a feature is not clear in a C program, it is particularly useful while using templates. Consider,&lt;br /&gt;&lt;br /&gt;template &amp;lt;class T&amp;gt;&lt;br /&gt;T FOO (void) {&lt;br /&gt;  return T(); // Default construction&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;template &amp;lt;class T&amp;gt;&lt;br /&gt;T BAR (void) {&lt;br /&gt;  return FOO&amp;lt;T&amp;gt;(); // Syntactic consistency. Same for int, void and everything else.&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main (void) {&lt;br /&gt;  BAR&amp;lt;void&amp;gt;();&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;It suddenly makes sense when templates are in picture. Take home point: Syntactic consistency is of paramount importance for supporting generic programming and writing generic libraries.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/13960885-2451788015292327094?l=cpptruths.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CppTruths/~4/E1SzNDv0Cbw" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://cpptruths.blogspot.com/feeds/2451788015292327094/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=13960885&amp;postID=2451788015292327094" title="11 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/2451788015292327094?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/2451788015292327094?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CppTruths/~3/E1SzNDv0Cbw/return-void.html" title="return void" /><author><name>Sumant</name><uri>http://www.blogger.com/profile/11957855386259543653</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="28" height="32" src="http://4.bp.blogspot.com/--0WncXMeBPA/TchxRepk7bI/AAAAAAAABXo/oLNnYnw0K7A/s1600/Sumant-Tambe.JPG" /></author><thr:total>11</thr:total><feedburner:origLink>http://cpptruths.blogspot.com/2008/07/return-void.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DUIBSH85fyp7ImA9WxdQFEg.&quot;"><id>tag:blogger.com,1999:blog-13960885.post-2366353409414853990</id><published>2008-06-14T09:22:00.002-06:00</published><updated>2008-06-14T09:32:39.127-06:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-06-14T09:32:39.127-06:00</app:edited><title>Non-Virtual Interface and the Fragile Base Class Interface Problem</title><content type="html">A new &lt;a href="http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-Virtual_Interface"&gt;writeup&lt;/a&gt; on Non-Virtual Interface (NVI) idiom has been written on &lt;a href="http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms"&gt;More C++ Idioms&lt;/a&gt; wikibook. In the writeup, I discuss the relationship of NVI with the &lt;a href="http://www.cs.cmu.edu/~aldrich/papers/savcbs04.pdf"&gt;Fragile Base Class&lt;/a&gt; (FBC) problem, which can silently break perfectly good derived classes because of some innocuous changes in the base class.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/13960885-2366353409414853990?l=cpptruths.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CppTruths/~4/qkWPug3NfDE" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://cpptruths.blogspot.com/feeds/2366353409414853990/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=13960885&amp;postID=2366353409414853990" title="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/2366353409414853990?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/2366353409414853990?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CppTruths/~3/qkWPug3NfDE/non-virtual-interface-and-fragile-base.html" title="Non-Virtual Interface and the Fragile Base Class Interface Problem" /><author><name>Sumant</name><uri>http://www.blogger.com/profile/11957855386259543653</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="28" height="32" src="http://4.bp.blogspot.com/--0WncXMeBPA/TchxRepk7bI/AAAAAAAABXo/oLNnYnw0K7A/s1600/Sumant-Tambe.JPG" /></author><thr:total>2</thr:total><feedburner:origLink>http://cpptruths.blogspot.com/2008/06/non-virtual-interface-and-fragile-base.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DEEBRn09fCp7ImA9WxdTFk4.&quot;"><id>tag:blogger.com,1999:blog-13960885.post-2390756785094476245</id><published>2008-05-12T17:19:00.003-06:00</published><updated>2008-05-12T17:57:37.364-06:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-05-12T17:57:37.364-06:00</app:edited><title>RSS Feed for More C++ Idioms Wikibook</title><content type="html">The open-content wikibook "More C++ Idioms" has grown quite a bit from it inception. Whenever I get time, I try to add more contents in the book. So I always wanted to track the changes happening in the book in a convenient manner. Today, I put together a &lt;a href="http://feeds.feedburner.com/MoreCppIdiomsWikibook"&gt;RSS feed&lt;/a&gt; for the book, which publishes recent changes made to the book. Thanks to the excellent technical support provided by existing wikibookians (if that is a word). The feed is formatted like two column GUI-based diff utilities (kdiff3, Beyond-compare). Frankly, it is not as readable and enjoyable as regular blog entries but at least it will help interested readers to know what new content is being added to the book and how the book making progress towards completion.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/13960885-2390756785094476245?l=cpptruths.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CppTruths/~4/iKXDTO2YXsY" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://cpptruths.blogspot.com/feeds/2390756785094476245/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=13960885&amp;postID=2390756785094476245" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/2390756785094476245?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/2390756785094476245?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CppTruths/~3/iKXDTO2YXsY/rss-feed-for-more-c-idioms-wikibook.html" title="RSS Feed for More C++ Idioms Wikibook" /><author><name>Sumant</name><uri>http://www.blogger.com/profile/11957855386259543653</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="28" height="32" src="http://4.bp.blogspot.com/--0WncXMeBPA/TchxRepk7bI/AAAAAAAABXo/oLNnYnw0K7A/s1600/Sumant-Tambe.JPG" /></author><thr:total>1</thr:total><feedburner:origLink>http://cpptruths.blogspot.com/2008/05/rss-feed-for-more-c-idioms-wikibook.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DkMMQnkyfSp7ImA9WxZbGEQ.&quot;"><id>tag:blogger.com,1999:blog-13960885.post-1953550998705170424</id><published>2008-04-22T13:26:00.003-06:00</published><updated>2008-04-22T14:01:23.795-06:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-04-22T14:01:23.795-06:00</app:edited><title>Redirecting C++ Truths feed</title><content type="html">Dear readers,&lt;br /&gt;&lt;br /&gt;Thanks for your continued interest in the C++ Truths blog and a steady stream of feedback comments. For quite some time now, I'm interested in learning accurate statistics about the readers of this blog. Recently, I came across, &lt;a href="http://www.feedburner.com"&gt;FeedBurner&lt;/a&gt;, which seems to be a popular choice for centralized feed processing and maintaining feed analytics such as subscriber count, live hits and many more things. Therefore, I have decided to redirect all the future contents on C++ Truths blog to the &lt;a href="http://feeds.feedburner.com/CppTruths"&gt;CppTruths&lt;/a&gt; feed. Existing atom and rss feeds shall be discontinued soon. I encourage you to subscribe to the new feed source and help me find the real subscriber count. In return, I promise to be more regular and frequent in posting more C++ truths, which you love to read!! &lt;br /&gt;&lt;br /&gt;- Sumant.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/13960885-1953550998705170424?l=cpptruths.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CppTruths/~4/CRA4pHb6iSo" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://cpptruths.blogspot.com/feeds/1953550998705170424/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=13960885&amp;postID=1953550998705170424" title="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/1953550998705170424?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/1953550998705170424?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CppTruths/~3/CRA4pHb6iSo/redirecting-c-truths-feed.html" title="Redirecting C++ Truths feed" /><author><name>Sumant</name><uri>http://www.blogger.com/profile/11957855386259543653</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="28" height="32" src="http://4.bp.blogspot.com/--0WncXMeBPA/TchxRepk7bI/AAAAAAAABXo/oLNnYnw0K7A/s1600/Sumant-Tambe.JPG" /></author><thr:total>2</thr:total><feedburner:origLink>http://cpptruths.blogspot.com/2008/04/redirecting-c-truths-feed.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DEYBSHkycCp7ImA9WxdTEEk.&quot;"><id>tag:blogger.com,1999:blog-13960885.post-2562098398259430233</id><published>2008-01-04T11:47:00.001-07:00</published><updated>2008-05-05T21:55:59.798-06:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-05-05T21:55:59.798-06:00</app:edited><title>Function Template Overload Resolution and Specialization Anomaly</title><content type="html">I recently realized that function template overloading and function template specialization can interact with each other in complex ways giving rise to quite surprising C++ programs. Consider,&lt;br /&gt;&lt;br /&gt;template&amp;lt;class T&amp;gt; // (a) a base template&lt;br /&gt;void f( T ) {&lt;br /&gt;  std::cout &amp;lt;&amp;lt; "f(T)\n";&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;template&amp;lt;&amp;gt;&lt;br /&gt;void f&amp;lt;&amp;gt;(int*) { // (b) an explicit specialization&lt;br /&gt;  std::cout &amp;lt;&amp;lt; "f(int *) specilization\n";&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;template&amp;lt;class T&amp;gt; // (c) another, overloads (a)&lt;br /&gt;void f( T* ) {&lt;br /&gt;  std::cout &amp;lt;&amp;lt; "f(T *)\n";&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main (void) {&lt;br /&gt;    int *p = 0;&lt;br /&gt;    f(p);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;Output of the above program is "f(T *)" (i.e. (c) is invoked in main). Now simply swap the order in which (b) and (c) are written. The output of the program changes! This time it invokes (b) giving output as "f(int *) specilization".&lt;br /&gt;&lt;br /&gt;The reason behind it is that when the integer full specilization (b) of f is defined in the order shown above, it is a full specialization of (a). But (c) is a better match as it is an overloaded primary template defined afterwards and we get "f(T *)" as an output. &lt;br /&gt;&lt;br /&gt;When (b) is defined after (c), (b) is an integer full specilization of (c) and hence the specilization is chosen as expected. &lt;br /&gt;&lt;br /&gt;An excerpt from the book "C++ Templates - The Complete Guide" helps explain what is really happening here.&lt;br /&gt;&lt;br /&gt;"Partial specialization doesn't introduce a completely new template: It is an extension of an existing template (the primary template). When a CLASS template is looked up, only primary templates are considered at first. If, after the selection of a primary template, it turns out that there is a partial specialization of that template with a template argument pattern that matches that of the instantiation, its definition (in other words, its body) is instantiated instead of the definition of the primary template. (Full template specializations work exactly the same way.)"&lt;br /&gt;&lt;br /&gt;(Added this para on May-05-2008)&lt;br /&gt;Note that the above paragraph applies to class templates only. But when full specializations are in consideration, the above paragraph applies to function templates as well. Full function template specialization is supported by C++98 standard but not partial function template specialization. A better alternative to partial function template specialization is to use plain old function overloading. Having said that, as far as I know, there are efforts begin made towards standardizing partial function template specialization for C++09 standard. (please see comments for more discussion on this.)&lt;br /&gt;&lt;br /&gt;The program clearly shows that the order of definition of specilizations and overloads affects primary template lookup. As a result, interestingly enough, you can define the f&amp;lt;&amp;gt;(int *) full specialization twice in the program. One after (a) and another one after (c) and program compiles just fine!&lt;br /&gt;&lt;br /&gt;template&amp;lt;class T&amp;gt; // (a) a base template&lt;br /&gt;void f( T ) {&lt;br /&gt;  std::cout &amp;lt;&amp;lt; "f(T)\n";&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;template&amp;lt;&amp;gt;&lt;br /&gt;void f&amp;lt;&amp;gt;(int*) { // (b) an explicit specialization&lt;br /&gt;  std::cout &amp;lt;&amp;lt; "f(int *) specilization\n";&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;template&amp;lt;class T&amp;gt; // (c) another, overloads (a)&lt;br /&gt;void f( T* ) {&lt;br /&gt;  std::cout &amp;lt;&amp;lt; "f(T *)\n";&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;template&amp;lt;&amp;gt;&lt;br /&gt;void f&amp;lt;&amp;gt;(int*) { // (d) another identical explicit specialization&lt;br /&gt;  std::cout &amp;lt;&amp;lt; "f(int *) another specilization\n";&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main (void) {&lt;br /&gt;    int *p = 0;&lt;br /&gt;    f(p);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;What is the output here? Any guesses?&lt;br /&gt;&lt;br /&gt;This program is an example of complexity that results due to orthogonality of C++ language. In simple terms, number of C++ features can co-exist and their interplay can baffle any uninitiated C++ programmer! I wonder how complex it would be once we have partial function template specialization support in standard C++ in 2009.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/13960885-2562098398259430233?l=cpptruths.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CppTruths/~4/QcLaeNDktKE" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://cpptruths.blogspot.com/feeds/2562098398259430233/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=13960885&amp;postID=2562098398259430233" title="5 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/2562098398259430233?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/2562098398259430233?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CppTruths/~3/QcLaeNDktKE/function-template-overload-resolution.html" title="Function Template Overload Resolution and Specialization Anomaly" /><author><name>Sumant</name><uri>http://www.blogger.com/profile/11957855386259543653</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="28" height="32" src="http://4.bp.blogspot.com/--0WncXMeBPA/TchxRepk7bI/AAAAAAAABXo/oLNnYnw0K7A/s1600/Sumant-Tambe.JPG" /></author><thr:total>5</thr:total><feedburner:origLink>http://cpptruths.blogspot.com/2008/01/function-template-overload-resolution.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DEIAQ3o9fSp7ImA9WB9VEkk.&quot;"><id>tag:blogger.com,1999:blog-13960885.post-6078817443456284175</id><published>2007-11-28T01:14:00.000-07:00</published><updated>2007-11-28T03:42:22.465-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2007-11-28T03:42:22.465-07:00</app:edited><title>using std::copy on std::map iterator pair</title><content type="html">Sometimes it is useful to be able iterate over all the elements of a std::map using standard algorithms like std::copy(), std::count(), std::min_element(), std::max_element(). These standard functions do not work out of the box using std::map::iterator. For example, if you want to print all the elements of a map to standard output, you can't use the following popular copy-ostream_iterator idiom. &lt;br /&gt;&lt;br /&gt;std::map &amp;lt;std::string, int&amp;gt; m;&lt;br /&gt;std::copy (m.begin(), m.end(), std::ostream_iterator&amp;lt;int&amp;gt;(std::cout, "\n")); &lt;br /&gt;// does not compile&lt;br /&gt;&lt;br /&gt;This is because value_type of the map::iterator is a pair. In other words, if iter is a map&amp;lt;T,U&amp;gt;::iterator then *iter gives pair&amp;lt;T,U&amp;gt; and not U. If we could somehow get hold of pair::second (i.e. type U) instead of pair&amp;lt;T,U&amp;gt; all the above mentioned algorithms can be used out of the box. &lt;br /&gt;&lt;br /&gt;The approach I took to solve this problem is to write an iterator adaptor that behaves likes any general bidirectional_iterator. In general, this approach allows map iterators to be used wherever Iterator-Pair idiom is useful. The code given below is kind of long but quite straight forward and idiomatic in nature.&lt;br /&gt;&lt;br /&gt;#include &amp;lt;map&amp;gt;&lt;br /&gt;#include &amp;lt;iostream&amp;gt;&lt;br /&gt;#include &amp;lt;algorithm&amp;gt;&lt;br /&gt;#include &amp;lt;string&amp;gt;&lt;br /&gt;#include &amp;lt;list&amp;gt;&lt;br /&gt;#include &amp;lt;iterator&amp;gt;&lt;br /&gt;&lt;br /&gt;template &amp;lt;class BiDirIter&amp;gt;&lt;br /&gt;class StdMapIteratorAdaptor &lt;br /&gt;/* To make the custom iterator behave like a standard iterator by exposing&lt;br /&gt;   required iterator_traits */&lt;br /&gt;  : public&lt;br /&gt;    std::iterator &amp;lt;std::bidirectional_iterator_tag,&lt;br /&gt;                   typename BiDirIter::value_type::second_type&amp;gt;&lt;br /&gt;{&lt;br /&gt;    BiDirIter iter_;&lt;br /&gt;  public:&lt;br /&gt;&lt;br /&gt;    explicit StdMapIteratorAdaptor(BiDirIter const &amp; iter = BiDirIter())&lt;br /&gt;      : iter_(iter) {}&lt;br /&gt;&lt;br /&gt;    bool operator == (StdMapIteratorAdaptor const &amp; rhs) const {&lt;br /&gt;      return (iter_ == rhs.iter_);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    bool operator != (StdMapIteratorAdaptor const &amp; rhs) const {&lt;br /&gt;      return !(*this == rhs);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    /* Return type is const to make it work with map::const_iterator */&lt;br /&gt;    typename BiDirIter::value_type::second_type const &amp; operator * () {&lt;br /&gt;      return iter_-&amp;gt;second;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    typename BiDirIter::value_type::second_type const &amp; operator * () const {&lt;br /&gt;      return iter_-&amp;gt;second;&lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;    typename BiDirIter::value_type::second_type const * operator -&amp;gt; () const {&lt;br /&gt;      return &amp;(iter_-&amp;gt;second);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // Pre-increment&lt;br /&gt;    StdMapIteratorAdaptor &amp; operator ++ () {&lt;br /&gt;      ++iter_;&lt;br /&gt;      return *this;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // Post-increment&lt;br /&gt;    const StdMapIteratorAdaptor operator ++ (int) {&lt;br /&gt;      StdMapIteratorAdaptor temp (iter_);&lt;br /&gt;      ++iter_;&lt;br /&gt;      return temp;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // Pre-decrement&lt;br /&gt;    StdMapIteratorAdaptor &amp; operator -- () {&lt;br /&gt;      --iter_;&lt;br /&gt;      return *this;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // Post-decrement&lt;br /&gt;    const StdMapIteratorAdaptor operator -- (int) {&lt;br /&gt;      StdMapIteratorAdaptor temp (iter_);&lt;br /&gt;      --iter_;&lt;br /&gt;      return temp;&lt;br /&gt;    }&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;/* An helper function to save some typing of tedious nested C++ types &lt;br /&gt;   It is very similar to std::make_pair function */&lt;br /&gt;template &amp;lt;class BiDirIter&amp;gt;&lt;br /&gt;StdMapIteratorAdaptor &amp;lt;BiDirIter&amp;gt; &lt;br /&gt;make_map_iterator_adaptor (BiDirIter const &amp; iter)&lt;br /&gt;{&lt;br /&gt;  return StdMapIteratorAdaptor&amp;lt;BiDirIter&amp;gt; (iter);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main(void)&lt;br /&gt;{&lt;br /&gt;  typedef std::map &amp;lt;std::string, int&amp;gt; StrIntMap;&lt;br /&gt;  StrIntMap months;&lt;br /&gt;  &lt;br /&gt;  months["january"] = 31;&lt;br /&gt;  months["february"] = 28;&lt;br /&gt;  months["march"] = 31;&lt;br /&gt;  months["april"] = 30;&lt;br /&gt;  months["may"] = 31;&lt;br /&gt;  months["june"] = 30;&lt;br /&gt;  months["july"] = 31;&lt;br /&gt;  months["august"] = 31;&lt;br /&gt;  months["september"] = 30;&lt;br /&gt;  months["october"] = 31;&lt;br /&gt;  months["november"] = 30;&lt;br /&gt;  months["december"] = 31;&lt;br /&gt; &lt;br /&gt;  StrIntMap const &amp; m = months;&lt;br /&gt;&lt;br /&gt;  StdMapIteratorAdaptor &amp;lt;StrIntMap::const_iterator&amp;gt; begin (m.begin());&lt;br /&gt;  StdMapIteratorAdaptor &amp;lt;StrIntMap::const_iterator&amp;gt; end (m.end());&lt;br /&gt;  std::copy(begin, end, std::ostream_iterator &amp;lt;int&amp;gt; (std::cout, " "));&lt;br /&gt;  std::cout &amp;lt;&amp;lt; std::endl;&lt;br /&gt;  &lt;br /&gt;  std::list&amp;lt;int&amp;gt; l(make_map_iterator_adaptor(m.begin()), &lt;br /&gt;                         make_map_iterator_adaptor(m.end()));&lt;br /&gt;&lt;br /&gt;  std::copy (l.begin(), l.end(), std::ostream_iterator &amp;lt;int&amp;gt; (std::cout, " "));&lt;br /&gt;  std::cout &amp;lt;&amp;lt; std::endl;&lt;br /&gt;  std::copy (make_map_iterator_adaptor(months.begin()), &lt;br /&gt;             make_map_iterator_adaptor(months.end()), &lt;br /&gt;             std::ostream_iterator &amp;lt;int&amp;gt; (std::cout, " "));&lt;br /&gt;&lt;br /&gt;  return 0;&lt;br /&gt;}&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/13960885-6078817443456284175?l=cpptruths.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CppTruths/~4/McTFAaV6_2E" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://cpptruths.blogspot.com/feeds/6078817443456284175/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=13960885&amp;postID=6078817443456284175" title="6 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/6078817443456284175?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/6078817443456284175?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CppTruths/~3/McTFAaV6_2E/using-stdcopy-on-stdmap-iterator-pair.html" title="using std::copy on std::map iterator pair" /><author><name>Sumant</name><uri>http://www.blogger.com/profile/11957855386259543653</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="28" height="32" src="http://4.bp.blogspot.com/--0WncXMeBPA/TchxRepk7bI/AAAAAAAABXo/oLNnYnw0K7A/s1600/Sumant-Tambe.JPG" /></author><thr:total>6</thr:total><feedburner:origLink>http://cpptruths.blogspot.com/2007/11/using-stdcopy-on-stdmap-iterator-pair.html</feedburner:origLink></entry><entry gd:etag="W/&quot;D0EMQHsyfip7ImA9WB5UEU4.&quot;"><id>tag:blogger.com,1999:blog-13960885.post-1348790343413774838</id><published>2007-08-14T17:38:00.000-06:00</published><updated>2007-08-14T17:54:41.596-06:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2007-08-14T17:54:41.596-06:00</app:edited><title>New book on modern C++ idioms</title><content type="html">For quite some time now, I am hoping to come across a book on modern C++ idiom as comprehensive as the Purple book by James Coplien! Finally, I got bored of the long wait and a thought came to my mind - This is Web 2.0 and open knowledge era. Why don't I start writing myself? and ask the world to contribute to it? So here we go! A new free, open book on modern C++ idioms called &lt;a href=http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms&gt;More C++ Idioms&lt;/a&gt; is taking shape on &lt;a href="http://en.wikibooks.org"&gt;en.wikibooks.org&lt;/a&gt; And everyone's invited!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/13960885-1348790343413774838?l=cpptruths.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CppTruths/~4/4cO-mAuMmNs" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://cpptruths.blogspot.com/feeds/1348790343413774838/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=13960885&amp;postID=1348790343413774838" title="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/1348790343413774838?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/1348790343413774838?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CppTruths/~3/4cO-mAuMmNs/new-book-on-c-idioms.html" title="New book on modern C++ idioms" /><author><name>Sumant</name><uri>http://www.blogger.com/profile/11957855386259543653</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="28" height="32" src="http://4.bp.blogspot.com/--0WncXMeBPA/TchxRepk7bI/AAAAAAAABXo/oLNnYnw0K7A/s1600/Sumant-Tambe.JPG" /></author><thr:total>2</thr:total><feedburner:origLink>http://cpptruths.blogspot.com/2007/08/new-book-on-c-idioms.html</feedburner:origLink></entry><entry gd:etag="W/&quot;A08HSHg4cCp7ImA9WB5XFkQ.&quot;"><id>tag:blogger.com,1999:blog-13960885.post-730828019468810473</id><published>2007-07-17T13:11:00.000-06:00</published><updated>2007-07-17T13:17:19.638-06:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2007-07-17T13:17:19.638-06:00</app:edited><title>const overload functions taking char pointers</title><content type="html">Always have two overloaded versions of functions that take&lt;br /&gt;char * and const char * parameters. Declare (but don't define if not needed) &lt;br /&gt;a function that takes const char* as a parameter when you have defined &lt;br /&gt;a function that accepts a non-const char* as a parameter. &lt;br /&gt;&lt;br /&gt;#include &amp;lt;iostream&amp;gt;&lt;br /&gt;#include &amp;lt;iomanip&amp;gt;&lt;br /&gt;&lt;br /&gt;static void foo (char *s) {&lt;br /&gt;  std::cout &amp;lt;&amp;lt; "non-const " &amp;lt;&amp;lt; std::hex &amp;lt;&amp;lt; static_cast &amp;lt;void *&amp;gt;(s) &amp;lt;&amp;lt; std::endl;&lt;br /&gt;}&lt;br /&gt;static void foo (char const *s) {&lt;br /&gt;  std::cout &amp;lt;&amp;lt; "const " &amp;lt;&amp;lt; std::hex &amp;lt;&amp;lt; static_cast &amp;lt;void const *&amp;gt;(s) &lt;&lt; std::endl;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main (void)&lt;br /&gt;{&lt;br /&gt;  char * c1 = "Literal String 1";&lt;br /&gt;  char const * c2 = "Literal String 1";&lt;br /&gt;  foo (c1);&lt;br /&gt;  foo (c2);&lt;br /&gt;  foo ("Literal String 1");&lt;br /&gt;  //*c1 = 'l'; // This will cause a seg-fault on Linux.&lt;br /&gt;  std::cout &amp;lt;&amp;lt; c2 &amp;lt;&amp;lt; std::endl;&lt;br /&gt;&lt;br /&gt;  return 0;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;Because of default conversion rule from string literal to char *, &lt;br /&gt;the call to foo using in-place literal goes completely undetected &lt;br /&gt;through the eyes of compiler's type system.&lt;br /&gt;&lt;br /&gt;Interestingly enough, the addresses of all the identical string literals&lt;br /&gt;is the same, irrespective of whether it is assigned to const or non-const.&lt;br /&gt;Internally though, they are stored on the const DATA page and modifying&lt;br /&gt;them causes a seg-fault.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/13960885-730828019468810473?l=cpptruths.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CppTruths/~4/tIV9uBoeuAA" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://cpptruths.blogspot.com/feeds/730828019468810473/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=13960885&amp;postID=730828019468810473" title="6 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/730828019468810473?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/730828019468810473?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CppTruths/~3/tIV9uBoeuAA/const-overload-functions-taking-char.html" title="const overload functions taking char pointers" /><author><name>Sumant</name><uri>http://www.blogger.com/profile/11957855386259543653</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="28" height="32" src="http://4.bp.blogspot.com/--0WncXMeBPA/TchxRepk7bI/AAAAAAAABXo/oLNnYnw0K7A/s1600/Sumant-Tambe.JPG" /></author><thr:total>6</thr:total><feedburner:origLink>http://cpptruths.blogspot.com/2007/07/const-overload-functions-taking-char.html</feedburner:origLink></entry><entry gd:etag="W/&quot;A0AFQX4_eSp7ImA9WB5QF0g.&quot;"><id>tag:blogger.com,1999:blog-13960885.post-7959811628467204478</id><published>2007-07-06T15:30:00.000-06:00</published><updated>2007-07-06T16:08:30.041-06:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2007-07-06T16:08:30.041-06:00</app:edited><title>Future of C++ track @ ACCU</title><content type="html">Recently held &lt;a href="http://www.accu.org/index.php/conferences/accu_conference_2007/accu2007_schedule"&gt;ACCU 2007&lt;/a&gt; conference had a track dedicated to C++ called: Future of C++ Track. I have listed the presentations in that track and some other related presentations for a quick reference.&lt;br /&gt;&lt;br /&gt;* &lt;a href="http://www.accu.org/content/conf2007/Stroustrup-C++0x_An_Overview%20.pdf"&gt;An Outline of C++0x&lt;/a&gt; (Bjarne Stroustrup)&lt;br /&gt;* &lt;a href="http://www.accu.org/content/conf2007/Maurer-C++0x_Generating_Constant_Expression.pdf"&gt;Generalizing Constant Expressions in C++&lt;/a&gt; (Jens Maurer)&lt;br /&gt;* &lt;a href="http://www.accu.org/content/conf2007/Stroustrup-C++0x_Initializers.pdf"&gt;C++0x Initilaisation: Lists and a Uniform Syntax&lt;/a&gt; (Bjarne Stroustrup)&lt;br /&gt;* &lt;a href="http://www.accu.org/content/conf2007/Hinnant-C++0x_Rvalue_Reference.pdf"&gt;An Introduction to the Rvalue Reference in C++0x&lt;/a&gt; (Howard Hinnant)&lt;br /&gt;* &lt;a href="http://www.accu.org/content/conf2007/Winder-C++HasNoUsefulPurpose.pdf"&gt;C++ has no useful purpose&lt;/a&gt; (Russel Winder)&lt;br /&gt;* C++ Modules (David Vandevoorde)&lt;br /&gt;* Support for Numerical Programming in C++ (Walter Brown)&lt;br /&gt;* C++ Threads (Lawrence Crowl)&lt;br /&gt;* Standard Library report (Alisdair Meredith)&lt;br /&gt;* Concepts: An Introduction to Concepts in C++0x (Doug Gregor) (&lt;a href="http://www.research.att.com/~bs/oopsla06.pdf"&gt;OOPSLA06 paper&lt;/a&gt;)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/13960885-7959811628467204478?l=cpptruths.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CppTruths/~4/7Nc0JBYXY4c" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://cpptruths.blogspot.com/feeds/7959811628467204478/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=13960885&amp;postID=7959811628467204478" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/7959811628467204478?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/7959811628467204478?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CppTruths/~3/7Nc0JBYXY4c/future-of-c-track-accu.html" title="Future of C++ track @ ACCU" /><author><name>Sumant</name><uri>http://www.blogger.com/profile/11957855386259543653</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="28" height="32" src="http://4.bp.blogspot.com/--0WncXMeBPA/TchxRepk7bI/AAAAAAAABXo/oLNnYnw0K7A/s1600/Sumant-Tambe.JPG" /></author><thr:total>1</thr:total><feedburner:origLink>http://cpptruths.blogspot.com/2007/07/future-of-c-track-accu.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DE4HQHY8cSp7ImA9WBFbFU0.&quot;"><id>tag:blogger.com,1999:blog-13960885.post-7756559262133931505</id><published>2007-05-06T20:39:00.001-06:00</published><updated>2007-05-06T21:02:11.879-06:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2007-05-06T21:02:11.879-06:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="traits compile-time algorithm selection templates" /><title>iterator tags idiom and compile-time algorithm selection</title><content type="html">Compile-time algorithm selection can be done using function overloading and &lt;a href="http://accu.org/index.php/journals/442"&gt;traits idiom&lt;/a&gt;. It is a quite useful technique in generic programming. In this technique usually a set of "selector" types are used to select one among many overloaded functions. Note that the number of parameters to these overloaded functions is same but there is a "selector" type at the end of the parameter list. A use of that technique based on standard defined iterator tags is shown &lt;a href="http://www.mpi-inf.mpg.de/~kettner/courses/lib_design_03/notes/stl.html#Iterator2"&gt;here&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/13960885-7756559262133931505?l=cpptruths.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/CppTruths/~4/PXytaVj7-8s" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://cpptruths.blogspot.com/feeds/7756559262133931505/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=13960885&amp;postID=7756559262133931505" title="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/7756559262133931505?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/13960885/posts/default/7756559262133931505?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/CppTruths/~3/PXytaVj7-8s/iterator-tags-idiom-and-compile-time_06.html" title="iterator tags idiom and compile-time algorithm selection" /><author><name>Sumant</name><uri>http://www.blogger.com/profile/11957855386259543653</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="28" height="32" src="http://4.bp.blogspot.com/--0WncXMeBPA/TchxRepk7bI/AAAAAAAABXo/oLNnYnw0K7A/s1600/Sumant-Tambe.JPG" /></author><thr:total>2</thr:total><feedburner:origLink>http://cpptruths.blogspot.com/2007/05/iterator-tags-idiom-and-compile-time_06.html</feedburner:origLink></entry></feed>

