    <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  :: Curiously Recursive Template Problems with Aspect Oriented Programming</title>
        <link>https://members.accu.org/index.php/journals/1916</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 #109 - June 2012 + 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/c310/">o109</a>
                    (7)
<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/c310-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c310+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;Curiously Recursive Template Problems with Aspect Oriented Programming</h1>
<p><strong>Author:</strong>&nbsp;Martin Moene</p>
<p>
<strong>Date:</strong> 02 June 2012 19:12:49 +01:00 or Sat, 02 June 2012 19:12:49 +01:00</p>
<p><strong>Summary:</strong>&nbsp;Hugo Arregui, Carlos Castro and Daniel Gutson work out how to combine two useful techniques.</p>
<p><strong>Body:</strong>&nbsp;<p>Aspect Oriented Programming (AOP) is a programming paradigm that makes possible to clearly express programs separated into â€˜aspectsâ€™, including appropriate isolation, composition and reuse of the aspect code [<a href="#[Kiczales97]">Kiczales97</a>]. AOP defines <em>weaving</em> as the process of composing the aspects into a single entity.</p>

<p>Independently, there are situations in which a base class needs to know its subclass, e.g. for type-safe downcasts. The <span class="pattern">Curiously Recurring Template Pattern</span> (CRTP) is a C++ idiom in which a class X derives from a class template instantiation using X itself as template argument [<a href="#[Abrahams04]">Abrahams04</a>]. This way, the base class can know the derived type.</p>

<p>Both AOP and the CRTP are widely adopted C++ programming techniques. In particular, there exists an AOP easy implementation using templates [<a href="#[Spinczyk05]">Spinczyk05</a>]. However, a C++ grammar incompatibility arises when combining AOP and CRTP. While there exists a C++ dialect called AspectC++ [<a href="#[Spinczyk05]">Spinczyk05</a>], we donâ€™t evaluate in this work its ability to combine AOP and CRTP since it requires its own compiler extensions and so its not standard C++. Here we look at a simple solution implemented in standard C++ that addresses the issue without any overhead penalty.</p>

<h2>Problems combining AOP + CRTP</h2>

<p>There are some situations where combining the benefits of AOP and CRTP are desirable; however, as we will show below, some problems arise when applying together the individual standard procedures of each technique.</p>

<p>The code in Listing 1 shows an attempt of adding functionality, through aspects, to a base class named <code>Number</code>.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
//basic class
class Number
{
  protected:
  UnderlyingType n;
};

//aspects
template &lt;class NextAspect&gt;
struct ArithmeticAspect: public NextAspect
{
  FULLTYPE operator+
    (const FULLTYPE&amp; other) const;
    // What type is FULLTYPE?
  FULLTYPE operator- 
    (const FULLTYPE&amp; other) const;
  FULLTYPE&amp; operator+= 
    (const FULLTYPE&amp; other);
  FULLTYPE&amp; operator-= 
    (const FULLTYPE&amp; other);
};

template &lt;class NextAspect&gt;
struct LogicalAspect : public NextAspect
{
  bool operator! () const;
  bool operator&amp;&amp; (const FULLTYPE&amp; other) const;
  bool operator|| (const FULLTYPE&amp; other) const;
};

//decorating Number with aspectual code
typedef LogicalAspect
  &lt;ArithmeticAspect&lt;Number &gt; &gt; MyIntegralType;
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 1</td>
	</tr>
</table>

<p>We can observe that the return type of ArithmeticAspectâ€™s operator <code>+</code> and <code>-</code> needs to know the â€˜complete typeâ€™ (<code>FULLTYPE</code>) when trying to extend the base class functionality through operator overloading. We will address this issue in the following sections.</p>

<h2>A minimal solution</h2>

<p>The basic principle of this solution does not differ in essence from the traditional solution mentioned before.</p>

<h3>Problem</h3>

<p><code>Number</code> takes the place of the last aspect in the aspects list. However, <code>Number</code> itself needs to know (as a template template argument) the aspects list, to which it itself belongs, leading to a â€˜chicken or eggâ€™ grammatical dilemma.</p>

<p>For example, if <code>Number</code> knew  the complete type, it could use it as a return type for its operators as shown in Listing 2.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
template &lt;template &lt;class&gt; class Aspects&gt;
class Number
{
  typedef Aspects&lt;Number&lt;Aspects&gt;&gt; FullType;
...
};
ArithmeticAspect&lt;Number&lt;ArithmeticAspect&gt;&gt;
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 2</td>
	</tr>
</table>

<p>This shows the weaving of a single aspect with CRTP, which works perfectly:</p>

<pre class="programlisting">
  LogicalAspect&lt;ArithmeticAspect&lt;Number&lt;??&gt;&gt;&gt;</pre>

<p>On the other hand, this exposes the problem when trying to weave one additional aspect, since it requires a template template argument, which the aspects lists canâ€™t grammatically fulfill as coded above.</p>

<p>We present two solutions: the first being the simplest using C++11â€™s template alias [<a href="#[Reis]">Reis</a>
], and the second using variadic templates (templates that take a variable number of arguments, recently introduced in C++11 [<a href="#[Gregor]">Gregor</a>]) as the only C++11â€™s feature, which in turn, can also be easily implemented in C++98 as well. Both use a common language idiom introduced next, which aims to be used as a library providing a friendly syntax and reduced reusable code.</p>

<h3>The proposed language idiom</h3>

<p>A possible solution would be to apply some handcrafted per-case base template aliases, as shown below:</p>

<pre class="programlisting">
  //with template alias:
  template &lt;class T&gt;
  using LogicalArithmeticAspect =
     LogicalAspect&lt;ArithmeticAspect&lt;T&gt;&gt;;

  //without template alias:
  template &lt;class T&gt;
  struct LogicalArithmeticAspect
  {
    typedef 
       LogicalAspect&lt;ArithmeticAspect&lt;T&gt;&gt; Type;
  };

and with minor changes in the Number
 base classâ€™s code, we could write the following declaration:
  LogicalArithmeticAspect
  &lt;
    Number&lt;LogicalArithmeticAspect&gt;
  &gt;
</pre>

<p>Although this does the trick it tends to be impractical, and also would increment linearly the number of related lines of code in terms of the amount of combinations to be used, which would cause a copy-paste code bloat.</p>

<p>However, we will look for a more generic way to address this issue, avoiding drone code cloning, and being able to encapsulate the method into a library.</p>

<p>Therefore, in order to provide a user-oriented and easy to use library, we'll use C++11â€™s new variadic-templates so we can cleanly express our intention: to â€˜decorateâ€™ the base class with a list of aspects. An example of what we intend to achieve is shown below:</p>

<pre class="programlisting">
  Decorate&lt;Number&gt;::with&lt;ArithmeticAspect,
                         LogicalAspect&gt;</pre>

<p>The  skeleton of the <code>Decorate</code> class is shown in Listing 3, the details of which will vary in the  solutions below.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
template
  &lt;template &lt;template &lt;class&gt; class&gt; class Base&gt;
class Decorate
{
  public:
    template&lt;template &lt;class&gt; class ... Aspects&gt;
    struct with
    {
      //...
    };

    //...

  private:
    struct Apply 
    { â€¦ 
    };
};
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 3</td>
	</tr>
</table>
 
<p>In both solutions, the <code>with</code> nested class and the <code>Apply</code> internal helper will have different implementations.</p>

<h2>Solution 1: Using C++11â€™s template alias</h2>

<p>In this solution, the <code>Decorate::with</code> implementation is as shown in Listing 4, and the internal helper <code>Apply</code> structure also uses templates aliases (see Listing 5).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
template&lt;template &lt;class&gt; class ... Aspects&gt;
struct with
{
  template &lt;class T&gt;
  using AspectsCombination = 
     typename Apply&lt;Aspects...&gt;::template Type&lt;T&gt;;
  typedef
    AspectsCombination
      &lt;Base&lt;AspectsCombination&gt;&gt; Type;
};
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 4</td>
	</tr>
</table>
 
<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
template&lt;template &lt;class&gt; class A1,
         template &lt;class&gt; class ... Aspects&gt;
struct Apply&lt;A1, Aspects...&gt;
{
  template &lt;class T&gt;
  using Type = A1
    &lt;typename Apply
       &lt;Aspects...&gt;::template Type&lt;T&gt;&gt;;
};
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 5</td>
	</tr>
</table>

<p>Despite the implementation between the two solutions differing, the purpose is the same and the underlying idea is explained next in the second solution.</p>

<h2>Solution 2: Not using C++11â€™s template alias</h2>

<p>In this solution, the <code>Decorate::with</code> implementation is as shown in Listing 6.</p>
 
<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
template&lt;template &lt;class&gt; class ... Aspects&gt;
struct with
{
  typedef typename Apply&lt;Aspects...&gt;::Type TypeP;
  typedef typename TypeP::template Binding
  &lt;
    Base&lt;TypeP::template Binding&gt;
  &gt;::Type Type;
};
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 6</td>
	</tr>
</table>

<h3>Combining aspects</h3>

<p>Now that we have a list of aspects, how could we combine them? The solution we propose is to create a <code>Binder</code> class, as shown in Listing 7.</p>
 
<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
struct None 
{
};
template &lt;template &lt;class&gt; class A,
   class B = None&gt;
struct Binder
{
  template &lt;class T&gt;
  struct Binding
  {
    typedef
      typename Binder&lt;A&gt;::template Binding
      &lt;
        typename B::template
         Binding&lt;T&gt;::Type
      &gt;::Type Type;
   };
};
template&lt;template &lt;class&gt; class T&gt;
struct Binder&lt;T, None&gt;
{
  template &lt;class P&gt;
  struct Binding
  {
    typedef T&lt;P&gt; Type;
  };
};
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 7</td>
	</tr>
</table>

<p><code>Binder</code> encapsulates an aspect (as a template template argument) within a complete type <code>Binder&lt;Aspect&gt;</code>. Additionally, it enables us to do a â€˜<code>bind</code>â€™ operation to the next aspect or base class, by accessing to the <code>Binding</code> inner class.</p>

<p>The way in which <code>Binder</code> finally allows us to construct the whole type is shown below.</p>

<pre class="programlisting">
  Binder&lt;ArithmeticAspect,
  Binder&lt;LogicalAspect&gt;&gt;::Binding&lt;Number&gt;::Type</pre>

<p>Letâ€™s analyze step-by-step this listing (from the innermost to the outermost definition):</p>

<ol>
	<li><code>Binder&lt;LogicalAspect&gt;</code> uses the second definition, it just provides a complete type for the aspect with a possibility to bind to another complete type</li>
	<li><code>Binder&lt;ArithmeticAspect, Binder&lt;LogicalAspect&gt;&gt;</code> uses the first definition.
		<p>The binding generates a <code>Binder</code> to the <code>ArithmeticAspect</code>, and binds it to <code>Binder&lt;LogicalAspect&gt;::Binding&lt;T&gt;</code> generating a template template argument combining both aspects. (In short, <code>Binder</code> generates a template template argument â€“ combining Arithmetic with Logical aspects â€“ to be used in the base class).</p>
	</li>
	<li>Finally, the type is injected into the base <code>Number</code> class.</li>
</ol>

<p>Since such an implementation is not immediately obvious, we have provided a simplified version in Listing 8 for illustration.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
template &lt;template &lt;class&gt; class A,
   class B = None&gt;
struct Binder
{
  template &lt;class T&gt;
  struct Binding
  {
    typedef 
       Binder&lt;A&gt;::Binding
       &lt;
         B::Binding&lt;T&gt;::Type
       &gt;::Type Type;
   };
};
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 8</td>
	</tr>
</table>

<p>Now weâ€™ve got a <code>Binder</code> that implements the weaving of aspects and finally inject them into the base class.</p>

<h3>Applying the list of Aspects to the Number class</h3>

<p>The only remaining detail is to apply our <code>Bind</code> class to the list of aspects. To do this, we define a helper structure called <code>Apply</code>, that recursively applies the <code>Binder</code> class to each aspect, as shown in Listing 9.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
template &lt;template &lt;class&gt; class ... Aspects&gt;
struct Apply;
  template &lt;template &lt;class&gt; class T&gt;
  struct Apply&lt;T&gt;
  {
    typedef Binder&lt;T&gt; Type;
  };
  
  template&lt;template &lt;class&gt; class A1,
    template &lt;class&gt; class ... Aspects&gt;
  struct Apply&lt;A1, Aspects...&gt;
  {
    typedef Binder&lt;A1, typename Apply
    &lt;
      Aspects...
    &gt;::Type&gt; Type;
  };

  template&lt;template &lt;class&gt; class ... Aspects&gt;
  struct with
  {
    typedef
      typename Apply&lt;Aspects...&gt;::Type TypeP;
    typedef
      typename TypeP::template Binding
      &lt;
        Base&lt;TypeP::template Binding&gt;
      &gt;::Type
    Type;
  };
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 9</td>
	</tr>
</table> 

<p>We use the <code>Apply</code> helper struct to generate a resulting aspect as the weaving of all the given aspects, and inject it to the base class.</p>

<p>Then <code>::Type</code> contains the type we needed, and thatâ€™s it!</p>

<h2>Using the library</h2>

<p>The library that implements this idiom provides two tools: the means to obtain the <code>FullType</code>, and the means to build it.</p>

<p>Listing 10 shows a way of obtaining the <code>FullType</code> with an <code>Aspect</code>.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
//basic class
template 
   &lt;template &lt;class&gt; class Aspects&gt;
   class Number
{
  typedef Aspects&lt;Number&lt;Aspects&gt;&gt; FullType;
  //...
};

// aspect example
template &lt;class NextAspect&gt;
struct ArithmeticAspect: public NextAspect
{
  typedef typename NextAspect::FullType FullType;
  FullType
     operator+ (const FullType&amp; other) const;
  // ...
};
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 10</td>
	</tr>
</table>

<p>Letâ€™s see a final example, using two of the aspects mentioned before:</p>

<pre class="programlisting">
  typedef Decorate&lt;Number&gt;::with&lt;ArithmeticAspect,
            LogicalAspect&gt;::Type
			ArithmeticLogicalNumber;</pre>

<p>Please note that both solutions presented before expose the same interface so this snippet is equally applicable to them.</p>

<h2>C++98 alternative and complete code</h2>

<p>The same idea can be implemented using typelists in previous C++ standards, such as C++98.</p>

<p>The complete code of the library and examples both for C++11 and C++98 can be accessed in <a href="http://cpp-aop.googlecode.com">http://cpp-aop.googlecode.com</a></p>

<h2>Final comments</h2>

<p>We think that the solution to the problem exposed in this article could become straightforward by enhancing the language with a reserved keyword to get the full type. We suggest to consider this problem for the next revision of the language standard.</p>

<h2>References</h2>

<p class="bibliomixed"><a id="[Abrahams04]">[Abrahams04]</a>  Abrahams, David; Gurtovoy, Aleksey. 2004. <em>C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond</em>. Addison-Wesley. ISBN 0-321-22725-5.</p>

<p class="bibliomixed"><a id="[Gregor]">[Gregor]</a>  Gregor, Douglas; JÃ¤rvi, Jaako; Powell, Gary. Variadic Templates (Revision 3). [N2080=06-0150]. Programming Language C++. Evolution Working Group.</p>

<p class="bibliomixed"><a id="[Kiczales97]">[Kiczales97]</a>  Kiczales, Gregor; John Lamping, Anurag Mendhekar, Chris Maeda, Cristina Lopes, Jean-Marc Loingtier, and John Irwin (1997). â€˜Aspect-Oriented Programmingâ€™. <em>Proceedings of the European Conference on Object-Oriented Programming</em>, vol.1241. pp. 220â€“242.</p>

<p class="bibliomixed"><a id="[Reis]">[Reis]</a>  Dos Reis, Gabriel; Stroustrup, Bjarne. Template Aliases (Revision 3). [N2258=07-0118]. Programming Language C++. Evolution Working Group.</p>

<p class="bibliomixed"><a id="[Spinczyk05]">[Spinczyk05]</a> Spinczyk, Olaf; Lohmann, Daniel; Urban, Matthias. â€˜AspectC++: an AOP Extension for C++â€™. <em>Software Developerâ€™s Journal</em>, pages 68-76, 05/2005.</p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
