    <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  :: Static Polymorphic Named Parameters in C++</title>
        <link>https://members.accu.org/index.php/articles/1852</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>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + Overload Journal #119 - February 2014</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/articles/">All</a>

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

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

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

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

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

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c334/">o119</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-334/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+334/">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;Static Polymorphic Named Parameters in C++</h1>
<p><strong>Author:</strong>&nbsp;Martin Moene</p>
<p>
<strong>Date:</strong> 05 February 2014 11:29:49 +00:00 or Wed, 05 February 2014 11:29:49 +00:00</p>
<p><strong>Summary:</strong>&nbsp;Adding parameters to an object can be messy. Martin Moene demonstrates how method chaining can make code more readable.</p>
<p><strong>Body:</strong>&nbsp;<p>For a new kind of measurement in our application for scanning probe microscopy [<a href="#[Wikipedia-a]">Wikipedia-a</a>], I need to construct a curve that consists of several kinds of segments. The curve can for example describe the movement of the tip perpendicular to the surface of the material investigated and what data shall be acquired.</p>

<p>Behaviour of segment types varies. One segment may describe how the surface is approached, another how to move away from the surface and yet another describes a dwell time. Such a curve is part of force-distance spectroscopy [<a href="#[Wikipedia-b]">Wikipedia-b</a>]. Figure 1 below shows what the researchers would like to do.</p>

<table class="sidebartable">
	<tr>
		<td><img src="http://accu.org/content/images/journals/ol119/Moene/Moene-1.png" /></td>
	</tr>
	<tr>
		<td class="title">Figure 1</td>
	</tr>
</table>

<p>To a large extent the structure of a curve is fixed and this structure can be created at compile-time. Some variation is required at run-time, which can be arranged for via parameters. The simplified code in Listing 1 illustrates this.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
#include &quot;curve.hpp&quot;

int main()
{
  // run-time configurable:
  const int  Nsweep    = 1;
  const bool skipR1    = false;
        auto scanner   = create_scanner  ( &quot;Z&quot; );
  const auto distance  = create_condition( &quot;123 nm&quot; );
  const auto threshold = create_condition( &quot;chan1&quot;, &quot;&lt;=&quot;, &quot;2.7 V&quot; );

  Curve curve;

  curve.times( Nsweep  )
    .scans( scanner )
    .add  ( Retract ().stop_on( distance  ) ).unless( skipR1 )
    .add  ( Approach().stop_on( threshold ) )
    .add  ( Retract ().stop_on( distance  ) )
    ;
  std::cout &lt;&lt; &quot;curve.sweep(): &quot;; curve.sweep();
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 1</td>
	</tr>
</table>

<p>The curve built describes that: Nsweep times, scanner <code>Z</code> retracts the tip from the material surface for 123 nm (unless skipped), then approaches the surface until the measured value of <code>chan1</code> reaches the threshold value of 2.7 V, and finishes with retracting 123 nm again (t1 and t2 are omitted). Note that the threshold condition depends on other information than the scan distance. It can have any unit that makes sense in the experiment.</p>

<p>In the real implementation, there are many more parameters. To keep it simple, several things such as data acquisition are omitted here. Another simplification is to use struct without access specifiers for all classes in the code.</p>

<p>Compiling and running the simplified program gives:</p>

<pre class="programlisting">
prompt&gt;g++ -Wall -Wextra -Weffc++ -std=c++11 \
-o curve.exe curve.cpp &amp;&amp; curve
curve.sweep(): RZL AZ&lt;= RZL</pre>

<p>The output <code>RZL AZ&lt;= RZL</code> indicates the type of segment, scanner and condition used for each segment: <code>R</code> for Retract, <code>A</code> for Approach, <code>Z</code> for ZAxisScanner, <code>&lt;=</code> for LessEqualCondition and <code>L</code> for LengthCondition.</p>

<h2>Fluent interface</h2>

<p>The construct sketched above evolved from the following (simplified) C++98 code (Visual C++ 6).</p>

<pre class="programlisting">
return CurveDefinition().
  sweep( sweepCount ).
  add( CurveSegmentPtr( new SweepCurveSegment
    ( scanner, condFalse, ... ) ) ).
  add( CurveSegmentPtr( new SweepCurveSegment
    ( scanner, condition, ... ) ) ).
  add( CurveSegmentPtr( new SweepCurveSegment
    ( scanner, condFalse, ... ) ) );</pre>
	
<p>Although the sketched curve may be adequate for many kinds of experiments, it is a simplification of a more general approach. Experience with an initial version of the code led the researchers to express several additional wishes. For example to be able to conditionally include a segment, to only perform it once, or to perform a collection of segments multiple times.</p>

<p>As you see, the new code expands on the use of method chaining [<a href="#[Wikipedia-d]">Wikipedia-d</a>], a key element of a fluent interface [<a href="#[Wikipedia-e]">Wikipedia-e</a>]. Method chaining is also known as the named parameter idiom. In addition to method chaining, other variations are imaginable, such as function-like modifiers. For example to include a segment in the first sweep only with <code>once( segment )</code> or to perform a collection of segments (a sub-curve or section) a number of times via <code>times( N, section )</code>.</p>

<p>The new code also moves the allocation of segments out of the fluent interface. This makes the code much more readable. It also leads to the main subject of this article: static polymorphic named parameters.</p>

<p>Thus, <em>the</em> reason to compose the curve in this way is to benefit from a clear and flexible notation. As an internal domain-specific language [<a href="#[Fowler08]">Fowler08</a>] it also helps researchers to recognise the curve they sketched in the code.</p>

<h2>Static polymorphism</h2>

<p>Now, letâ€™s examine how a curve is constructed. Curveâ€™s method <code>add()</code> creates dynamic segment objects from the non-dynamic temporary â€˜exemplarsâ€™. To create a dynamic copy of the segment of the original type, <code>add()</code> is templated.</p>

<pre class="programlisting">
  template&lt; typename T &gt;
  Curve &amp; Curve::add( T const &amp; segment )
  {
    segments.emplace_back(
      std::make_unique&lt;T&gt;( segment ) );
    return *this;
  }</pre>
  
  
<p>Note: <code>std::make_unique&lt;T&gt;()</code> is a C++14 feature [<a href="#[make_unique]">make_unique</a>].</p>

<p>Looking at above code, it becomes clear that a call like <code>Approach().stop_on(...)</code> must itself return an object of type <code>Approach</code> to add the right type of segment to the curve.</p>

<p>Here is the crux of this article. Do all types such as <code>Approach</code> require their own method <code>stop_on()</code> to return the appropriate type? Fortunately thatâ€™s not the case, thanks to the curiously recurring template pattern or CRTP. See [<a href="#[Wikipedia-a]">Wikipedia-e: Subclasses</a>] and [<a href="#[Wikipedia-f])">Wikipedia-f</a>] respectively. (See Listing 2.)</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
template &lt;typename Derived&gt;
struct SegmentParameter : SegmentCommon
{
#define self crtp_cast&lt;Derived&gt;(*this)

    Derived &amp; stop_on( ConditionPtr cond )
    {
        condition( cond );
        return self;
    }

#undef self
};

struct Approach : SegmentParameter&lt;Approach&gt;
{
   // inherited: 
   // Approach &amp; stop_on( ConditionPtr s );
};
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 2</td>
	</tr>
</table>

<p>With this construct <code>Approach</code> can inherit <code>stop_on()</code> that returns the desired <code>Approach &amp;</code> instead of <code>SegmentParameter &amp;</code>. The <code>crtp_cast </code>combined with a macro enables us to write <code>return self</code> to return the current object <em>with the right type</em> where we would otherwise write <code>return *this</code> [<a href="#[Bendersky11]">Bendersky11</a>]. The shortest of four <code>crtp_cast </code>const-volatile variations is:</p>

<pre class="programlisting">
  template&lt;class D, class B&gt;
  D &amp; crtp_cast(B &amp; p)
  { return static_cast&lt;D &amp;&gt;( p ); }</pre>
  
<p>For an interesting discussion about encapsulation and the CRTP, see Better Encapsulation for the Curiously Recurring Template Pattern by Alexander Nasonov [<a href="#[Nasonov05]">Nasonov05</a>].</p>

<h2>Build to use</h2>

<p>In the end weâ€™ve built a curve that contains a collection of smart-pointered segments that originate in interface <code>Segment</code>. At the same time the curve is a segment itself, so that it can act as a sub-curve or section of another curve. See the following derivation chains.</p>

<pre class="programlisting">
  Curve â†’ SegmentParameter&lt;Curve&gt; â†’ SegmentCommon â†’  Segment
  Approach â†’ SegmentParameter&lt;Approach&gt; â†’ SegmentCommon â†’ Segment
  ...</pre>
  
<p>Thus, whereas construction of the curve builds on automatic â€˜exemplarâ€™ objects and static polymorphism via the CRTP compile-time technique, using the curve occurs via classical dynamic polymorphism with <code>Segment</code> as the interface.</p>

<h2>Letting go of the garbage</h2>

<p>One little thing worries me: the code for the sequence <code>curve.add(...).unless(...)</code> is both elegant and inelegant at the same time. It is simple, but then it lets you create a segment to only throw it away immediately via <code>unless()</code>.</p>

<pre class="programlisting">
  Curve &amp; unless( bool skip )
  {
    if ( skip )
      segments.pop_back();
    return *this;
  }</pre>
  
<p>One can argue that recycling is good and more garbage means more recycling, but that isn't entirely in line with Bjarne Stroustrupâ€™s idea [<a href="#[Kalev13]">Kalev13</a>]:</p>

<p class="blockquote">So, I say that C++ is my favorite GC language because it generates so little garbage.</p>

<p>As a reviewer pointed out, one may circumvent the awkward situation by prefixing the condition, or by including it in a conditional add function like so:</p>

<pre class="programlisting">
  curve.enable_if_not( skipR1 )
    .add( Retract ().stop_on( distance ) );
  curve.add_if_set( performR1,
    Retract ().stop_on( distance ) );</pre>
	
<p>However, to ease reading of consecutive lines, Iâ€™d prefer to keep the left part of the lines similar, as illustrated here.</p>

<pre class="programlisting">
  curve.add_if( Retract ().stop_on( distance  ), performR1 )
       .add   ( Approach().stop_on( threshold ) );</pre>
  
<p>Weâ€™re leaving the realms of fluid interfaces and named parameters though.</p>

<h2>Summary</h2>

<p>In this article a fluent interface is applied to a simplified setting for scanning probe spectroscopy. The resulting code shows a close relationship to the graphic representation provided by the researchers. The main point of the article is to show how one can obtain the static inheritance required for named parameters in this setting via the curiously recurring template pattern.</p>

<h2>Acknowledgements</h2>

<p>Iâ€™d like to thank the <em>Overload</em> team for reviewing the article and Jonathan Wakely for clarifying several aspects of smartpointers. Their remarks and suggestions were key in improving the article.</p>

<h2>Notes and references</h2>

<p>Code for this article and code for a larger example with modifiers <code>once</code> and <code>times</code> is available on [<a href="#[GitHub]">GitHub</a>].</p>

<p class="bibliomixed"><a id="[Arena12]"></a>[Arena12] Use CRTP for polymorphic chaining. Marco Arena. 29 April 2012. <a href="http://marcoarena.wordpress.com/2012/04/29/use-crtp-for-polymorphic-chaining/">http://marcoarena.wordpress.com/2012/04/29/use-crtp-for-polymorphic-chaining/</a> (Presents a slightly different application of the CRTP.)</p>

<p class="bibliomixed"><a id="[Bendersky11]"></a>[Bendersky11] The Curiously Recurring Template Pattern in C++. Eli Bendersky. 17 May 2011. <a href="http://eli.thegreenplace.net/2011/05/17/the-curiously-recurring-template-pattern-in-c/">http://eli.thegreenplace.net/2011/05/17/the-curiously-recurring-template-pattern-in-c/</a> (Mentions <code>crtp_cast</code> in a comment.)</p>
 
<p class="bibliomixed"><a id="[Fowler05]"></a>[Fowler05] Fluent Interface. Martin Fowler. 20 December 2005.<a href="http://www.martinfowler.com/bliki/FluentInterface.html">http://www.martinfowler.com/bliki/FluentInterface.html</a></p>

<p class="bibliomixed"><a id="[Fowler08]"></a>[Fowler08] Domain-Specific Language. Martin Fowler. 15 May 2008. <a href="http://martinfowler.com/bliki/DomainSpecificLanguage.html">http://martinfowler.com/bliki/DomainSpecificLanguage.html</a></p>

<p class="bibliomixed"><a id="[GitHub]"></a>[GitHub] Code for Static polymorphic named parameters in C++. Martin Moene. 31 December 2013. <a href="https://github.com/martinmoene/martin-moene.blogspot.com/tree/master/Static%20polymorphic%20named%20parameters%20in%20C%2B%2B">https://github.com/martinmoene/martin-moene.blogspot.com/tree/master/Static polymorphic named parameters in C++</a></p>

<p class="bibliomixed"><a id="[K-ballo13]"></a>[K-ballo13] Episode Eight: The Curious Case of the Recurring Template Pattern. <em>Tales of C++ K-ballo</em>. 2 December 2013.<a href="http://talesofcpp.fusionfenix.com/post-12/episode-eight-the-curious-case-of-the-recurring-template-pattern">http://talesofcpp.fusionfenix.com/post-12/episode-eight-the-curious-case-of-the-recurring-template-pattern</a></p>

<p class="bibliomixed"><a id="[Kalev13]"></a>[Kalev13] An Interview with Bjarne Stroustrup. Danny Kalev and Bjarne Stroustrup. May 15, 2013. <a href="http://www.informit.com/articles/article.aspx?p=2080042">http://www.informit.com/articles/article.aspx?p=2080042</a></p>

<p class="bibliomixed"><a id="[make_unique] "></a>[make_unique] make_unique. <em>CppReference</em>. <a href="http://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique">http://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique</a> Here, function <code>make_unique&lt;&gt;()</code> is equivalent to <code>std::unique_ptr&lt;T&gt;(new T(std::forward&lt;Args&gt;(args)...))</code>. See also Herb Sutterâ€™s GotW #89 Solution: Smart Pointers (<a href="http://herbsutter.com/2013/05/29/gotw-89-solution-smart-pointers/">http://herbsutter.com/2013/05/29/gotw-89-solution-smart-pointers/</a>) and GotW #102: Exception-Safe Function Calls (<a href="http://herbsutter.com/gotw/_102/">http://herbsutter.com/gotw/_102/</a>).</p>

<p class="bibliomixed"><a id="[Nasonov05]"></a>[Nasonov05] Better encapsulation for the curiously recurring template pattern. Alexander Nasonov. <em>Overload</em>, 70:11-13, December 2005 (<a href="http://accu.org/index.php/journals/296">http://accu.org/index.php/journals/296</a>).</p>

<p class="bibliomixed">[<a id="[Wikipedia-a]"></a>Wikipedia-a] Scanning Probe Microscopy. <em>Wikipedia</em>. <a href="http://en.wikipedia.org/wiki/Scanning_probe_microscopy">http://en.wikipedia.org/wiki/Scanning_probe_microscopy</a> Accessed 21 December 2013.</p>
 
<p class="bibliomixed"><a id="[Wikipedia-b]"></a>[Wikipedia-b] Force-Distance spectroscopy . <em>Wikipedia</em>.<a href="http://en.wikipedia.org/wiki/Atomic_force_microscopy#Force_spectroscopy">http://en.wikipedia.org/wiki/Atomic_force_microscopy#Force_spectroscopy</a> Accessed 19 December 2013. See also [<a href="#[Wikipedia-c])">Wikipedia-c</a>].</p>

<p class="bibliomixed"><a id="[Wikipedia-c]"></a>[Wikipedia-c] Scanning tunneling spectroscopy. <em>Wikipedia</em>. <a href="http://en.wikipedia.org/wiki/Scanning_tunneling_spectroscopy">http://en.wikipedia.org/wiki/Scanning_tunneling_spectroscopy</a> Accessed 19 December 2013.</p>
 
<p class="bibliomixed"><a id="[Wikipedia-d]"></a>[Wikipedia-d] Method chaining or named parameter idiom. <em>Wikipedia</em>. <a href="http://en.wikipedia.org/wiki/Method_chaining">http://en.wikipedia.org/wiki/Method_chaining</a> Accessed 16 December 2013. See also [Wikipedia-e].</p>

<p class="bibliomixed"><a id="[Wikipedia-e]"></a>[Wikipedia-e] Fluent interface. <em>Wikipedia</em>. <a href="http://en.wikipedia.org/wiki/Fluent_interface">http://en.wikipedia.org/wiki/Fluent_interface</a> Accessed 21 December 2013. See also [<a href="#[Fowler05])">Fowler05</a>]</p>

<p class="bibliomixed"><a id="[Wikipedia-f]"></a>[Wikipedia-f] Curiously recurring template pattern (CRTP). <em>Wikipedia</em>. <a href="http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern">http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern</a> Accessed 17 December 2013. See also [<a href="#[K-ballo13])">K-ballo13</a>], [<a href="#[Bendersky11])">Bendersky11</a>], [<a href="#[Arena12])">Arena12</a>].</p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
