    <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  :: Better Encapsulation for the Curiously Recurring Template Pattern</title>
        <link>https://members.accu.org/index.php/journals/296</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 #70 - Dec 2005 + 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/c142/">70</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/c142-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c142+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;Better Encapsulation for the Curiously Recurring Template Pattern</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 02 December 2005 05:00:00 +00:00 or Fri, 02 December 2005 05:00:00 +00:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="section" lang="en">
<div class="titlepage">
<h2><a name="d0e18" id="d0e18"></a></h2>
</div>
<p>C++ has a long, outstanding history of tricks and idioms. One of
the oldest is the curiously recurring template pattern (CRTP)
identified by James Coplien in 1995 [<a href=
"#Coplien">Coplien</a>]. Since then, CRTP has been popularized and
is used in many libraries, particularly in Boost [<a href=
"#Boost">Boost</a>]. For example, you can find it in <tt class=
"classname">Boost.Iterator</tt>, <tt class=
"classname">Boost.Python</tt> or in <tt class=
"classname">Boost.Serialization</tt> libraries.</p>
<p>In this article I assume that a reader is already familiar with
CRTP. If you would like to refresh your memory, I would recommend
reading chapter 17 in [<a href="#Vandevoorde-">Vandevoorde-</a>].
This chapter is available for free on <a href=
"http://www.informit.com" target="_top">www.informit.com</a>.</p>
<p>If you look at the curiously recurring template pattern from an
OO perspective you'll notice that it shares common properties with
OO frameworks (e.g. Microsoft Foundation Classes) where base class
member functions call virtual functions implemented in derived
classes. The following code snippet demonstrates OO framework style
in its simplest form:</p>
<pre class="programlisting">
// Library code
class Base
{
  public:
    virtual ~Base();
    int foo() { return this-&gt;do_foo(); }

  protected:
    virtual int do_foo() = 0;
};
</pre>
<p>Here, <tt class="classname">Base::foo</tt> calls virtual
function <tt class="function">do_foo</tt>, which is declared as a
pure virtual function in <tt class="classname">Base</tt> and,
therefore, it must be implemented in derived classes. Indeed, a
body of do_foo appears in class <tt class=
"classname">Derived</tt>:</p>
<pre class="programlisting">
// User code
class Derived : public Base
{
  private:
    virtual int do_foo() { return 0; }
};
</pre>
<p>What is interesting here, is that an access specifier of
<tt class="function">do_foo</tt> has been changed from protected to
private. It's perfectly legal in C++ and it takes a second to type
one simple word. What is more, it's done intentionally to emphasize
that <tt class="function">do_foo</tt> isn't for public use. (A user
may go further and hide the whole <tt class="function">Derived</tt>
class if she thinks it's worth it.)</p>
<p>The moral of the story is that a user should be able to hide
implementation details of the class easily.</p>
<p>Now let us assume that restrictions imposed by virtual functions
are not affordable and the framework author decided to apply
CRTP:</p>
<pre class="programlisting">
// Library code
template&lt;class DerivedT&gt;
class Base
{
  public:
    DerivedT&amp; derived() {
       return static_cast&lt;DerivedT&amp;&gt;(*this); }
    int foo() {
       return this-&gt;derived().do_foo(); }
};
// User code
class Derived : public Base&lt;Derived&gt;
{
  public:
    int do_foo() { return 0; }
};
</pre>
<p>Although <tt class="function">do_foo</tt> is an implementation
detail, it's accessible from everywhere. Why not make it private or
protected? You'll find an answer inside function foo. As you see,
the function calls <tt class="function">Derived::do_foo</tt>. In
other words, base class calls a function defined in a derived class
directly.</p>
<p>Now, let's find an easiest way for a user to hide implementation
details of <tt class="classname">Derived</tt>. It should be very
easy; otherwise, users won't use it. It can be a bit trickier for
the author of <tt class="classname">Base</tt> but it still should
be easy to follow.</p>
<p>The most obvious way of achieving this is to establish a
friendship between <tt class="classname">Base</tt> and <tt class=
"classname">Derived</tt>:</p>
<pre class="programlisting">
// User code
class Derived : public Base&lt;Derived&gt;
{
  private:
    friend class Base&lt;Derived&gt;;
    int do_foo() { return 0; }
};
</pre>
<p>This solution is not perfect for one simple reason: the friend
declaration is proportional to the number of template parameters of
<tt class="classname">Base</tt> class template. It might get quite
long if you add more parameters.</p>
<p>To get rid of this problem one can fix the length of the friend
declaration by introducing a non-template <tt class=
"classname">Accessor</tt> that forwards calls:</p>
<pre class="programlisting">
// Library code
class Accessor
{
  private:
    template&lt;class&gt; friend class Base;
    template&lt;class DerivedT&gt;
    static int foo(DerivedT&amp; derived)
    {
        return derived.do_foo();
    }
};
</pre>
<p>The function <tt class="function">Base::foo</tt> should call
<tt class="function">Accessor::foo</tt> which in turn calls
<tt class="function">Derived::do_foo</tt>. A first step of this
call chain is always successful because the <tt class=
"classname">Base</tt> is a friend of <tt class=
"classname">Accessor</tt>:</p>
<pre class="programlisting">
// Library code
template&lt;class DerivedT&gt;
class Base
{
  public:
    DerivedT&amp; derived() {
       return static_cast&lt;DerivedT&amp;&gt;(*this); }
    int foo() {
       return Accessor::foo(this-&gt;derived()); }
};
</pre>
<p>The second step succeeds only if either <tt class=
"function">do_foo</tt> is public or if the <tt class=
"classname">Accessor</tt> is a friend of <tt class=
"classname">Derived</tt> and <tt class="function">do_foo</tt> is
protected. We are interested only in a second alternative:</p>
<pre class="programlisting">
// User code
class Derived : public Base&lt;Derived&gt;
{
  private:
    friend class Accessor;
    int do_foo() { return 0; }
};
</pre>
<p>This approach is taken by several boost libraries. For example,
<tt class="classname">def_visitor_access</tt> in <tt class=
"classname">Boost.Python</tt> and <tt class=
"classname">iterator_core_access</tt> in <tt class=
"classname">Boost.Iterator</tt> should be declared as friends in
order to access user-defined private functions from <tt class=
"classname">def_visitor</tt> and <tt class=
"classname">iterator_facade</tt> respectively.</p>
<p>Even though this solution is simple, there is a way to omit the
friend declaration. This is not possible if <tt class=
"function">do_foo</tt> is private - you will have to change that to
protected. The difference between these two access specifiers is
not so important for most CRTP uses. To understand why, take a look
at how you derive from CRTP base class:</p>
<pre class="programlisting">
class Derived : public Base&lt;Derived&gt; { /* ... */ };
</pre>
<p>Here, you pass the final class to <tt class=
"classname">Base</tt>'s template arguments list.</p>
<p>An attempt to derive from <tt class="classname">Derived</tt>
doesn't give you any advantage because the <tt class=
"classname">Base&lt;Derived&gt;</tt> class knows only about
<tt class="classname">Derived</tt>.</p>
<p>Our goal is to access protected function <tt class=
"function">Derived::do_foo</tt> from the <tt class=
"classname">Base</tt>:</p>
<pre class="programlisting">
// User code
class Derived : public Base&lt;Derived&gt;
{
  protected:
    // No friend declaration here!
    int do_foo() { return 0; }
};
</pre>
<p>Normally, you access a protected function declared in a base
class from its child. The challenge is to access it the other way
around.</p>
<p>The first step is obvious. The only place for our interception
point where a protected function can be accessed is a descendant of
<tt class="classname">Derived</tt>:</p>
<pre class="programlisting">
struct BreakProtection : Derived
{
    static int foo(Derived&amp; derived) {
       /* call do_foo here */ }
};
</pre>
<p>An attempt to write</p>
<pre class="programlisting">
   return derived.do_foo();
</pre>
<p>inside <tt class="function">BreakProtection::foo</tt> fails
because it's forbidden according to the standard, paragraph
11.5:</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>When a friend or a member function of a derived class references
a protected nonstatic member of a base class, an access check
applies in addition to those described earlier in clause 11. Except
when forming a pointer to member (5.3.1), the access must be
through a pointer to, reference to, or object of the derived class
itself (or any class derived from that class) (5.2.5).</p>
</blockquote>
</div>
<p>The function can only be accessed through an object of type
<tt class="classname">BreakProtection</tt>.</p>
<p>Well, if the function can't be called directly, let's call it
indirectly. Taking an address of <tt class="function">do_foo</tt>
is legal inside <tt class="classname">BreakProtection</tt>
class:</p>
<pre class="programlisting">
    &amp;BreakProtection::do_foo;
</pre>
<p>There is no <tt class="function">do_foo</tt> inside <tt class=
"classname">BreakProtection</tt>, therefore, this expression is
resolved as <tt class="literal">&amp;Derived::do_foo</tt>. Public
access to a pointer to protected member function has been granted!
It's time to call it:</p>
<pre class="programlisting">
struct BreakProtection : Derived
{
  static int foo(Derived&amp; derived)
  {
    int (Derived::*fn)() =
       &amp;BreakProtection::do_foo;
    return (derived.*fn)();
  }
};
</pre>
<p>For better encapsulation, the <tt class=
"classname">BreakProtection</tt> can be moved to the private
section of <tt class="classname">Base</tt> class template. The
final solution is:</p>
<pre class="programlisting">
// Library code
template&lt;class DerivedT&gt;
class Base
{
  private:
    struct accessor : DerivedT
    {
        static int foo(DerivedT&amp; derived)
        {
            int (DerivedT::*fn)() 
               = &amp;accessor::do_foo;
            return (derived.*fn)();
        }
    };
  public:
    DerivedT&amp; derived() {
       return static_cast&lt;DerivedT&amp;&gt;(*this); }
    int foo() { return accessor::foo(
       this-&gt;derived()); }
};
// User code
struct Derived : Base&lt;Derived&gt;
{
  protected:
    int do_foo() { return 1; }
};
</pre>
<p>Note that the user code is slightly shorter and cleaner than in
the first solution. The library code has similar complexity.</p>
<p>There is a downside to this approach, though. Many compilers
don't optimize away function pointer indirection even if it's
called in-place:</p>
<pre class="programlisting">
return (derived.*(&amp;accessor::do_foo))();
</pre>
<p>The main strength of CRTP over virtual functions is better
optimization.</p>
<p>CRTP is faster because there is no virtual function call
overhead and it compiles to smaller code because no type
information is generated. The former is doubtful for the second
solution while the latter still holds. Hopefully, future versions
of popular compilers will implement this kind of optimization.
Also, it's less convenient to use member function pointers,
especially for overloaded functions.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e277" id="d0e277"></a>References</h2>
</div>
<div class="bibliomixed"><a name="Coplien" id="Coplien"></a>
<p class="bibliomixed">[Coplien] James O. Coplien. &quot;Curiously
Recurring Template Patterns&quot;, <span class="citetitle"><i class=
"citetitle">C++ Report</i></span>, February 1995.</p>
</div>
<div class="bibliomixed"><a name="Vandevoorde-" id=
"Vandevoorde-"></a>
<p class="bibliomixed">[Vandevoorde-] David Vandevoorde, Nicolai M.
Josuttis. &quot;<span class="citetitle"><i class="citetitle">C++
Templates: The Complete Guide</i></span>&quot;. <span class=
"bibliomisc"><a href=
"http://www.informit.com/articles/article.asp?p=31473" target=
"_top">http://www.informit.com/articles/article.asp?p=31473</a></span></p>
</div>
<div class="bibliomixed"><a name="Boost" id="Boost"></a>
<p class="bibliomixed">[Boost] Boost libraries. <span class=
"bibliomisc"><a href="http://www.boost.org" target=
"_top">http://www.boost.org</a></span>.</p>
</div>
<div class="bibliomixed"><a name="standard" id="standard"></a>
<p class="bibliomixed">[standard] ISO-IEC 14882:1998(E),Programming
languages - C++.</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
