    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Visiting Alice</title>
        <link>https://members.accu.org/index.php/journals/1996</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">Overload Journal #72 - Apr 2006 + Programming Topics</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c140/">72</a>
                    (6)
<br />

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c65/">Programming</a>
                    (877)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c140-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c140+65/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Visiting Alice</h1>
<p><strong>Author:</strong>&nbsp;Martin Moene</p>
<p>
<strong>Date:</strong> 01 April 2006 21:14:01 +01:00 or Sat, 01 April 2006 21:14:01 +01:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<p class="quote">&quot;The time has come,&quot; the Walrus said,<br> 
&quot;To talk of many things:<br> 
Of tuples, trees and composites;<br> 
Of visitors and kings.&quot;<sup><a href="#fn:1" rel="footnote">1</a></sup> </p>

<h2>Welcome </h2>
<p>â€œGood morning, everyone, and welcome to the Wonderland Social Club annual treasure hunt. I am the Walrus.â€ (<em>coo-coo coo-choo</em>) â€œWell, not a walrus, but I am quite long in the tooth.â€ (<em>groan</em>) </p>
<p>â€œThis year the clues are all in trees. On each clue sheet thereâ€™s a clue to an item of treasure. Some clue sheets also contain two further clues, which lead to more clue sheets. With each treasure clue there is an indication of the value of the treasure at that location.â€ </p>
<p>â€œYou have until 6 oâ€™clock this evening to find as much treasure as you can. The team with the most valuable hoard of treasure will be the winner. The first clue is outside in the garden. See you back here in the Carpenterâ€™s Arms at 6 oâ€™clock. Good luck everybody!â€ </p>
<h2>Planning the Route </h2>
<p>There were three teams: four trainee nurses called the Pre-Tenders, three employees of the Royal Mail called the Post Men and two publicans called the Inn Keepers. The Pre-Tenders decided to do the easy clues first; the Post Men chose to visit the nearest places first; and the Inn Keepers settled for finding the most valuable treasure first. </p>
<p>Overload readers will have spotted immediately that the treasure huntersâ€™ problem involves the traversal of an abstract binary tree. The Walrus had drawn the tree on a sheet of paper so that he could refer to it when he was adding up the scores at the end of the day. And, as it turned out, the Pre-Tenders would visit the treasure locations in pre-order sequence, the Post Men in post-order sequence and the Inn Keepers in in-order sequence. </p>
<h2>Encoding the Problem </h2>
<p>Bill, a nerdy-looking youth with thick oyster-shell glasses had spotted this, too. He was a C# programmer and was often to be seen in the corner of the bar with a beer and a lap-top. To him the treasure huntersâ€™ tree seemed to be a set of dynamically constructed, garbage collected, polymorphic objects. â€œItâ€™s a binary treeâ€, he said to his best mate, Ben. â€œYesâ€, agreed Ben, but Benâ€™s mental imagery was very different. â€œNested structsâ€, said Ben. </p>
<table class="sidebartable">
<tr>
<td>
<img style="margin-left:10%;margin-right:4em;float:left;max-width:40%;" src="http://accu.org/content/images/journals/ol72/Bass/Bass-tree.png">
<div><pre class="programlisting">struct L
{
    char a, i;
};
struct C
{
    L l;
    char e;
};
</pre></div>
</td>
</tr>
<tr>
<td class="title">Listing 1 - A simple tree as nested structs.</td>
</tr>
</table>

<p>Bill looked at him blankly for a moment, decided Ben must have been joking and replied with an ironic, â€œYeah, rightâ€. But Ben was a C++ programmer and he wasnâ€™t joking. â€œNo, reallyâ€ said Ben, pulling out his own lap-top, â€œLook, Iâ€™ll show you what I meanâ€. </p>

<p>Ben drew a tree with just five nodes, A, L, I, C and E, as shown in Listing 1. He defined classes for the root node, C, and the other non-leaf node L. For the leaf nodes he just used <code>chars</code>. </p>
<p>Bill was not impressed at all. â€œI thought you were a C++ programmerâ€, he retorted. â€œThatâ€™s C code. Where are the classes? Where are the methods? Whatâ€™s that public data doing there?â€ â€œThis just captures the <em>structure</em> of the treeâ€, Ben explained. â€œIâ€™ve used a <code>char</code> as a place-holder for the treasure clues and the value of the treasure.â€ </p>
<p>Bill wasnâ€™t convinced. Inserting his <em>Design Patterns</em> CD into his PC he brought up the Composite structure diagram and typed in an improved version of Benâ€™s classes. â€œEven I can write better C++ than thatâ€, Bill scoffed. Referring to the example in the <em>Design Patterns</em> book, Bill wrote the code shown in Listing 2. Now it was Benâ€™s turn to be unimpressed. Billâ€™s code was more than three times longer (32 non-blank lines to 9), it had more types in more complex relationships, it brought up apparently irrelevant implementation issues (such as using vectors or lists and how to implement <code>Leaf::push_back()</code>) and it was less efficient in time and space (particularly if the tree nodes were allocated on the heap). But Ben was more interested in other things. </p>

<table class="sidebartable">
<tr>
<td>
<pre class="programlisting">class Component
{
public:
    virtual ~Component() {}
    virtual void operation() = 0;
    virtual void push_back(Component*) = 0;

    typedef std::vector&lt;Component*&gt;::iterator Iterator;
    virtual Iterator begin() = 0;
    virtual Iterator end() = 0;
};

class Leaf : public Component
{
public:
    Leaf(int v) 
    : leaf_value(v) {}

    int value()
    {
        return leaf_value;
    }

private:
    virtual void operation()
    {
        /* . . . */
    }

    virtual void push_back(Component*)
    {
        throw &quot;Can't add to Leaf!&quot;;
    }

    virtual Iterator begin()
    {
        return children.begin();
    }

    virtual Iterator end()
    {
        return children.end();
    }

    int leaf_value;
    std::vector&lt;Component*&gt; children;
    // always empty
};

class Composite : public Component
{
private:
    virtual void operation()
    {
        /* . . . */
    }

    virtual void push_back(Component* c)
    {
        children.push_back(c);
    }

    virtual Iterator begin()
    {
        return children.begin();
    }

    virtual Iterator end()
    {
        return children.end();
    }

    std::vector&lt;Component*&gt; children;
};
</pre>
</td>
</tr>
<tr>
<td class="title">Listing 2 - Classes for the Composite Pattern in C++.</td>
</tr>
</table>

<p>â€œOKâ€, said Ben, in an uncharacteristically conciliatory tone, â€œbut your tree has to be built at run time and it gives special status to <code>Component::operation()</code>. What if the tree structure is fixed at compile time? And what if we want to capture the tree structure, but donâ€™t know what operations will be performed on the nodes?â€ Billâ€™s face fell. He could see what was coming. Any second now Ben was going to say something about those confounded C++ templates. Two of the trainee nurses from the Pre-Tenders team had been powdering their noses. As they came out of the Ladies and left the pub to start the treasure hunt Billâ€™s face brightened momentarily. But his brief reverie was broken by Benâ€™s words. â€œWe should be able to write a function template that applies an arbitrary function to each node in a tree. Any tree. Something like this.â€ And Ben typed in the code in Listing 3. </p>

<table class="sidebartable">
<tr>
<td>
<pre class="programlisting">int main()
{
    C tree = /* ... */;
    visit&lt;in_order&gt;(tree, Write(cout));
    return 0;
}
</pre>
</td>
</tr>
<tr>
<td class="title">Listing 3 - A generic tree visit function.</td>
</tr>
</table>

<p>â€œLetâ€™s stick with our 5-node tree and letâ€™s not worry about how itâ€™s created, for now. Write is a function object that writes information about a node to an <code>ostream</code>. And <code>visit</code> is a function template that walks the tree and calls a function (<code>Write</code> in this case) for each node. The <code>in_order</code> template parameter is a policy class that specifies in-order traversal.â€ </p>

<h2>The Generalised Visit Algorithm </h2>
<p>Thinking out loud, Ben said: â€œWhen we visit a node we need to apply the given function to the node itself and each of its child nodes. The parent defines a natural order on the children and weâ€™ll use that to visit each child in turn. The traversal policy defines when to visit the parent (before the children, after the children or somewhere in between). Itâ€™s like having a parent thatâ€™s an STL container of children and the traversal policy provides an iterator into the container â€“ except that it all happens at compile time. So the algorithm is: </p>
<ul>
<li>visit the children in the range [first, pvp) </li>
<li>visit the parent </li>
<li>visit the children in the range [pvp, last) where pvp is the â€˜parent visit positionâ€™ iterator obtained from the traversal policy.â€ </li>
</ul>
<p>Benâ€™s code is shown in Listing 4. </p>

<table class="sidebartable">
<tr>
<td>
<pre class="programlisting">template&lt;typename Traversal, typename Node, typename Op&gt;

void visit(Node&amp; root, Op op)
{
    typedef typename begin&lt;Node&gt;::type first;
    typedef typename end&lt;Node&gt;::type last;
    typedef typename Traversal::template apply&lt;Node&gt;::type pvp;

    children&lt;first, pvp&gt;::template visit_each&lt;Traversal&gt;(root, op);
    op(root);
    children&lt;pvp, last&gt;::template visit_each&lt;Traversal&gt;(root, op);
}
</pre>
</td>
</tr>
<tr>
<td class="title">Listing 4 - The generalised visit algorithm.</td>
</tr>
</table>

<p>At first this looked more like hieroglyphics than source code to Bill. He could see Benâ€™s â€œiteratorsâ€ <code>first</code>, <code>last</code> and <code>pvp</code>, but they were <em>types</em> and real iterators are <em>objects</em>. He could see function calls that seemed to correspond to the three steps of the visit algorithm, too, but it was far from clear how the <code>visit_each</code> functions would work. The â€œiteratorsâ€ were being used to instantiate the <code>children</code> class template instead of being passed to the <code>visit_each</code> function, so how could the function step through the children as the algorithm requires? </p>

<h2>Compile-Time Iterators </h2>
<p>Ben was well aware that the code needed some explanation. â€œCompile time algorithms work with constants and types, which are both immutableâ€, he went on. â€œThereâ€™s no such thing as a compile-time variable. Instead of incrementing an iterator we must create a new iterator pointing to the next element in the container. For example, the root node in our 5-node tree has two children: l and e. We could think of using a pointer-to-memberÂ­of-C as an iterator. Then an iterator to the first child of C would point to <code>C::l</code> and we can imagine incrementing that iterator to point to <code>C::e</code>. But C++ doesnâ€™t have a pointer-to-member-of-C type â€“ it only has pointer-to-member-of-C-of-type-L (<code>L C::*</code>); and that canâ€™t be incremented because it would change type in the process (becoming <code>int C::*</code>).â€ </p>

<p>Bill wasnâ€™t sure if he understood this, but he wasnâ€™t going to admit it, so he let Ben continue. â€œInstead we can define a metaÂ­function that takes a compile-time iterator as a template parameter and generates a new compile-time iterator pointing to the next element. Something like this.â€ Ben produced listing 5. </p>

<table class="sidebartable">
<tr>
<td>
<pre class="programlisting">template&lt;typename C, typename M, M C::*&gt; 
struct next;

template&lt;&gt;
struct next&lt;C, L, &amp;C::l&gt;
{
    static int L::* const value;
};

int C::* const next&lt;C, L, &amp;C::l&gt;::value = &amp;C::e;
</pre>
</td>
</tr>
<tr>
<td class="title">Listing 5 - The compile-time analogue of incrementing an iterator.</td>
</tr>
</table>

<p>â€œWe pass in <code>&amp;C::l</code> (as a template parameter) and we get out <code>&amp;C::e</code> (as a class static value).â€ </p>

<p>â€œBut thatâ€™s hideousâ€, said Bill. â€œIt is pretty uglyâ€, admitted Ben. â€œAnd it only works for child nodes that are accessible data members of the parent node, too. Thatâ€™s very limiting. But the <code>visit</code> function doesnâ€™t use pointer-to-member values as iterators â€“ it uses types, and thatâ€™s much more flexible.â€ </p>
<p>Ben was enjoying himself. â€œSuppose L was a base class of C instead of a memberâ€, he enthused. â€œWe canâ€™t use a pointer-toÂ­member value to identify a base class, but we can encode a pointer-to-member value as a type.â€ (In fact, the <code>next&lt;&gt;</code> metaÂ­function in Listing 5 does just that.) â€œAnd then we can use types as iterators to base classes <em>and</em> data members. Itâ€™s probably worth declaring class templates for these two families of types: <code>member_iterator&lt;&gt;</code> points to a node thatâ€™s a member of its parent and <code>base_iterator&lt;&gt;</code> points to a node thatâ€™s a base class sub-object of its parent.â€ </p>
<p>â€œIâ€™ll refer to these collectively as â€˜child iteratorsâ€™. The <code>begin&lt;&gt;</code> and <code>end&lt;&gt;</code> meta-functions can return classes instantiated from these templates for the <code>visit&lt;&gt;</code> function to use. Those metaÂ­functions are the compile-time analogue of the <code>begin()</code> and <code>end()</code> functions provided by STL containers.â€ </p>
<p>â€œOKâ€, said Bill slowly, still far from convinced, â€œWe canâ€™t increment these iterators, but we still have to compare them and dereference them, right? How do we do that?â€ </p>
<h2>Iterating Through the Children </h2>
<p>â€œThatâ€™s a good questionâ€, replied Ben. â€œWe need to see how the <code>visit_each&lt;&gt;</code> function works to answer that.â€ </p>
<p>â€œAs you can see, there are no loop constructs. There canâ€™t be because loops require a loop variable and there are no compile-time variables. So we use recursion instead. The idea is to visit the first child (by calling the <code>visit&lt;&gt;</code> function) and then call <code>visit_each&lt;&gt;</code>recursively to visit all the remaining children.â€ Ben paused to take another gulp of his Black Sheep bitter and Bill seized the opportunity to ask why <code>visit_each&lt;&gt;</code> is a static function of a template class. â€œIâ€™ll come to that in a minuteâ€, Bill responded, â€œbut for now you just need to know that the primary <code>children&lt;&gt;</code> template defines the general case and the specialisation provides the terminating condition for the recursion.â€ </p>
<p>Ben pondered for a moment before continuing. â€œIf <code>First</code> is a <code>member_iterator&lt;&gt;</code> the <code>visit_each&lt;&gt;</code> function can retrieve a pointer-to-member value from it, which must be bound to an object using the <code>.*</code> or <code>-&gt;*</code> operator before we can access the data member it refers to. We canâ€™t store an object reference or pointer in the iterator because itâ€™s a <em>compile-time</em> iterator and references and pointers are run-time entities â€“ they donâ€™t have a value at compile time. And that means we canâ€™t dereference a <code>member_iterator&lt;&gt;</code> â€“ it doesnâ€™t hold enough information. So, the <code>visit_each&lt;&gt;</code> function must bind a compile-time iterator to a (run-time) reference to the parent node, which produces a reference to the child node pointed to by the iterator. And, of course, if we have to do this for <code>member_iterator&lt;&gt;</code>s we should do the same for other child iterators such as <code>base_iterator&lt;&gt;</code>s.â€ </p>

<table class="sidebartable">
<tr>
<td>
<pre class="programlisting">template&lt;typename C, typename M, M C::*&gt; struct member_iterator;
template&lt;typename D, typename B&gt; struct base_iterator;
</pre>
</td>
</tr>
<tr>
<td class="title">Listing 6 - Member and base class iterators. </td>
</tr>
</table>

<p>â€œIs that clear?â€, asked Ben. â€œErrm, I think soâ€, said Bill, who wasnâ€™t used to thinking about the interaction of compile-time operations with the run-time environment. â€œSo, a child iterator is a type, not an object; it canâ€™t be incremented; and it canâ€™t be dereferenced. Thatâ€™s a weird sort of iterator!â€ Ben agreed, â€œWeird, yes, but itâ€™s still an iterator in my bookâ€. </p>
<p>Bill was studying the <code>visit_each&lt;&gt;</code> function and another question occurred to him: â€œ<code>bind&lt;&gt;</code> seems to be a class template with a nested function. Why isnâ€™t it just a template function?â€ â€œAhâ€, said Ben, â€œthatâ€™s so that we can define separate bind functions for member-iterators and base-iterators. If C++ supported partial specialisation of function templates we could define partial specialisations for each of the two iterator families; but it doesnâ€™t, so Iâ€™ve just put a static function in a class template and defined partial specialisations of the class template.â€ </p>

<table class="sidebartable">
<tr>
<td>
<pre class="programlisting">template&lt;typename First, typename Last&gt;
struct children
{
    template&lt;typename Traversal, typename Node, typename Op&gt;
    static void visit_each(Node&amp; node, Op op)
    {
        visit&lt;Traversal&gt;(bind&lt;First&gt;::function(node), op);

        typedef typename next&lt;First&gt;::type Next;

        children&lt;Next,Last&gt;::template visit_each&lt;Traversal&gt;(node, op);
    }
};

template&lt;typename Iter&gt;
struct children&lt;Iter, Iter&gt;
{
    template&lt;typename Traversal, typename Node, typename Op&gt;
    static void visit_each(Node&amp;, Op) {}
};
</pre>
</td>
</tr>
<tr>
<td class="title">Listing 7 - The visit_each&lt;&gt; function.</td>
</tr>
</table>

<p>Hardly pausing for breath Ben continued his commentary. â€œHere, the <code>parent&lt;&gt;</code> and <code>child&lt;&gt;</code> meta-functions just extract the type of the parent and child nodes from the child iterator.â€ (See Appendix 1.) â€œThe <code>member_iterator&lt;&gt;</code> specialisation uses the <code>.*</code> operator to bind a pointer-to-member to the parent; the <code>base_iterator&lt;&gt;</code> specialisation just uses the implicit conversion from derived class reference to base class reference.â€ (Although Ben didnâ€™t think to mention it, he could have used the Boost <code>enable_if&lt;&gt;</code> templates to define separate overloads of the bind function instead.) </p>

<table class="sidebartable">
<tr>
<td>
<pre class="programlisting">template&lt;typename Iter&gt; struct bind;

template&lt;typename C, typename M, M C::* member&gt;
struct bind&lt; member_iterator&lt;C, M, member&gt; &gt;
{
    typedef member_iterator&lt;C, M, member&gt; Iter;
    typedef typename child&lt;Iter&gt;::type Child;
    typedef typename parent&lt;Iter&gt;::type Parent;

    static Child&amp; function(Parent&amp; parent)
    {
        return parent.*member;
    }
};

template&lt;typename D, typename B&gt;
struct bind&lt; base_iterator&lt;D,B&gt; &gt;
{
    typedef base_iterator&lt;D,B&gt; Iter;
    typedef typename child&lt;Iter&gt;::type Child;
    typedef typename parent&lt;Iter&gt;::type Parent;

    static Child&amp; function(Parent&amp; parent)
    {
        return parent;
    }
};
</pre>
</td>
</tr>
<tr>
<td class="title">Listing 8 - Simulated partial specialisations of the bind function. </td>
</tr>
</table>

<p>Ben leant back in his chair with a satisfied smile. â€œThe rest is easyâ€, he said. â€œThe <code>visit_each&lt;&gt;</code> function uses the <code>next&lt;&gt;</code> meta-function to generate an iterator to the next child node and calls itself to visit the remaining children (if any). Eventually, the two iterators become equal and the <code>children&lt;Iter,Iter&gt;</code> specialisation comes into play. At that point an empty <code>visit_each&lt;&gt;</code> function is instantiated and the recursion terminates.â€ </p>
<p>Bill felt cheated. â€œSo we donâ€™t <em>compare</em> the iterators, eitherâ€, he said tetchily. â€œAt least, not explicitly.â€ â€œWell, no, I suppose notâ€, Ben replied with an air of superiority, â€œbut thatâ€™s how it is with compile-time algorithms.â€ </p>
<h2>Epilogue </h2>
<p>â€œGlad to see everyone back on timeâ€, said the Walrus cheerily. â€œNow, letâ€™s see how you all got on.â€ And with that he collected the clue sheets and sat down to work out what the teams had scored. Some 20 minutes later he stood up again and gravely announced that he had a problem â€“ all three teams had the same score! â€œSo Iâ€™ll offer a bonus point to the first team to find Tweedledum and Tweedledee.â€ One of the Pre-Tenders gave a little squeal, waved one hand in the air and pointed excitedly with the other in the direction of Bill and Ben. â€œItâ€™s themâ€, she cried. And everyone could see she was right. They looked like two peas in a pod and they were arguing like schoolboys. </p>
<p>â€œCompile-time is betterâ€, said Ben. â€œNah, run-timeâ€, insisted Bill. â€œCompile-time.â€ â€œRun-time.â€ ... </p>
<p>Phil Bass<br>
phil@stoneymanor.demon.co.uk </p>

<p>Full code listings provided in appendices. </p>

<h3>Appendix 1 â€“ Visit.hpp</h3>
<table class="sidebartable">
<tr>
<td>
<p>The following code implements the compile-time visit algorithm itself. </p>
</td>
</tr>
<tr>
<td>
<pre class="programlisting">struct nil {};
template&lt;typename Iter&gt; struct parent;
template&lt;typename Iter&gt; struct child;
template&lt;typename Iter&gt; struct bind;
template&lt;typename Iter&gt; struct next;
template&lt;typename C, typename M, M C::*&gt; struct member_iterator;

template&lt;typename C, typename M, M C::* member&gt;
struct parent&lt; member_iterator&lt;C,M,member&gt; &gt;
{
    typedef C type;
};

template&lt;typename C, typename M, M C::* member&gt;
struct child&lt; member_iterator&lt;C,M,member&gt; &gt;
{
    typedef M type;
};

template&lt;typename C, typename M, M C::* member&gt;
struct bind&lt; member_iterator&lt;C, M, member&gt; &gt;
{
    typedef member_iterator&lt;C, M, member&gt; Iter;
    typedef typename child&lt;Iter&gt;::type Child;
    typedef typename parent&lt;Iter&gt;::type Parent;

    static Child&amp; function(Parent&amp; parent)
    {
        return parent.*member;
    }
};

template&lt;typename D, typename B&gt; struct base_iterator;

template&lt;typename D, typename B&gt;
struct parent&lt; base_iterator&lt;D,B&gt; &gt;
{
    typedef D type;
};

template&lt;typename D, typename B&gt;
struct child&lt; base_iterator&lt;D,B&gt; &gt;
{
    typedef B type;
};

template&lt;typename D, typename B&gt;
struct bind&lt; base_iterator&lt;D,B&gt; &gt;
{
    typedef base_iterator&lt;D,B&gt; Iter;
    typedef typename child&lt;Iter&gt;::type Child;
    typedef typename parent&lt;Iter&gt;::type Parent;

    static Child&amp; function(Parent&amp; parent)
    {
        return parent;
    }
};

template&lt;typename T&gt; struct begin
{
    typedef nil type;
};

template&lt;typename T&gt; struct end
{
    typedef nil type;
};

template&lt;typename First, typename Last&gt; struct children;

template&lt;typename Traversal, typename Node, typename Op&gt;
void visit(Node&amp; root, Op op)
{
    typedef typename begin&lt;Node&gt;::type first;
    typedef typename end&lt;Node&gt;::type last;
    typedef typename Traversal::template apply&lt;Node&gt;::type pvp;

    children&lt;first, pvp&gt; ::template visit_each&lt;Traversal&gt;(root, op);
    op(root);
    children&lt;pvp, last&gt; ::template visit_each&lt;Traversal&gt;(root, op);
}

template&lt;typename First, typename Last&gt;
struct children
{
    template&lt;typename Traversal, typename Node, typename Op&gt;
    static
    void visit_each(Node&amp; node, Op op)
    {
        visit&lt;Traversal&gt; (bind&lt;First&gt;::function(node), op);
        typedef typename next&lt;First&gt;::type Next;
        children&lt;Next,Last&gt; ::template visit_each&lt;Traversal&gt;(node, op);
    }
};

template&lt;typename Iter&gt;
struct children&lt;Iter, Iter&gt;
{
    template&lt;typename Traversal, typename Node, typename Op&gt;
    static void visit_each(Node&amp;, Op) {}
};
</pre>
</td>
</tr>
</table>

<h3>Appendix 2 - Visiting Alice (with children as nested structs)</h3>
<table class="sidebartable">
<tr>
<td>
<p>A program using the visit algorithm described here needs to provide some information about the structure of the tree whose nodes are to be visited. This is done by defining suitable child-iterator types, the next&lt;iter&gt; meta-function, the begin&lt;node&gt; metaÂ­function and specialisations of the traversal order policy templates. The following code shows the definitions for the ALICE tree used in the main text. &lt;/node&gt;&lt;/iter&gt;</p>
</td>
</tr>
<tr>
<td>
<pre class="programlisting">struct L
{
    char a, i;
};

typedef member_iterator&lt;L, char, &amp;L::a&gt; L_a_iterator;
typedef member_iterator&lt;L, char, &amp;L::i&gt; L_i_iterator;

template&lt;&gt; struct next&lt;L_a_iterator&gt; { typedef L_i_iterator type; };
template&lt;&gt; struct next&lt;L_i_iterator&gt; { typedef nil          type; };
template&lt;&gt; struct begin&lt;L&gt;           { typedef L_a_iterator type; };

struct C
{
    L l;
    char e;
};

typedef member_iterator&lt;C, L,    &amp;C::l&gt; C_l_iterator;
typedef member_iterator&lt;C, char, &amp;C::e&gt; C_e_iterator;

template&lt;&gt; struct next&lt;C_l_iterator&gt; { typedef C_e_iterator type; };
template&lt;&gt; struct next&lt;C_e_iterator&gt; { typedef nil          type; };
template&lt;&gt; struct begin&lt;C&gt;           { typedef C_l_iterator type; };

struct in_order
{
    template&lt;typename T&gt; struct apply { typedef nil type; };
};

template&lt;&gt; struct in_order::apply&lt;C&gt; { typedef C_e_iterator type; };
template&lt;&gt; struct in_order::apply&lt;L&gt; { typedef L_i_iterator type; };
</pre>
</td>
</tr>
<tr>
<td>
<p>The traversal policy is in the form of a meta-function class (a class with a nested class template). This gives the flexibility of template template parameters while still allowing the policy to be used by compile-time algorithms operating on types. </p>
</td>
</tr>
</table>

<h3>Appendix 3 - Visiting Alice (with a base class as a child)</h3>
<table class="sidebartable">
<!--<tr>
<td class="title">Appendix 3 - Visiting Alice (with a base class as a child)</td>
</tr> -->
<tr>
<td>
<p>The case of the ALICE tree where L is a base class of C is only slightly different. The root node, C, needs a constructor and the child-iterator pointing to node L becomes a base_iterator&lt;&gt;. The following code shows the support required for node C (most of which is the same as for the example in which L is a member of C). </p>
</td>
</tr>
<tr>
<td>
<pre class="programlisting">struct C : L
{
    C(const L&amp; l, char e_) : L(l), e(e_) {}
    char e;
};

typedef base_iterator&lt;C, L&gt; C_l_iterator;
typedef member_iterator&lt;C, char, &amp;C::e&gt; C_e_iterator;

template&lt;&gt; struct next&lt;C_l_iterator&gt; { typedef C_e_iterator type; };
template&lt;&gt; struct next&lt;C_e_iterator&gt; { typedef nil          type; };
template&lt;&gt; struct begin&lt;C&gt;           { typedef C_l_iterator type; };
template&lt;&gt; struct in_order::apply&lt;C&gt; { typedef C_e_iterator type; };
</pre>
</td>
</tr>
<tr>
<td>
<p>For compile-time trees defined using tuples and inheritance it is possible to provide the child iterators in a library. For example, the
ALICE tree could be defined as:</p>
</td>
</tr>
<tr>
<td>
<pre class="programlisting">#include &lt;boost/tuple.hpp&gt;
using boost::tuple;
typedef tuple&lt;char,char&gt; L;
typedef tuple&lt;L,char&gt; C;
C tree = C( L('A','I'), 'E' );
</pre>
</td>
</tr>
<tr>
<td>
<p>Since Boost tuples are implemented using inheritance it is easy to provide predefined base-iterators and meta-functions supporting the visit&lt;&gt; algorithm. In this case, no information about the structure of the tree needs to be provided in the client code; visiting Alice comes for free. </p>
</td>
</tr>
</table>

<div class="footnotes">
<hr>
<ol>
<li id="fn:1">
<p>After Lewis Carollâ€™s â€œThe Walrus and the Carpenterâ€. By the way, he lied about the kings. &nbsp;<a href="#fnref:1" rev="footnote">â†©</a>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
