    <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  :: From Mechanism to Method:</title>
        <link>https://members.accu.org/index.php/journals/327</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 #58 - Dec 2003 + 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/c154/">58</a>
                    (8)
<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/c154-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c154+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;From Mechanism to Method:</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 02 December 2003 21:55:55 +00:00 or Tue, 02 December 2003 21:55:55 +00:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e20" id="d0e20"></a></h2>
<h3>Data Abstraction and Heterarchy</h3>
</div>
<p>Trees. Everywhere. Ones with green leaves, ones with family
members, ones with files and directories, ones with classes, and
many more. Trees - most often upside-down with the root at the top
and leaves at the bottom - offer a common and useful mechanism for
organizing program elements [<a href="#Jackson">Jackson</a>].
Strict hierarchies imply nesting and exclusive containment, e.g.,
singleinheritance hierarchies and organizational structures
blighted by antediluvian management thinking. In common use, the
term hierarchy also includes DAGs (directed acyclic graphs) that,
although hierarchical, are not strictly hierarchies. This is the
sense in which I will use it in this article because the world we
live and work in more accurately reflects the elasticity of this
usage, e.g., multiple-inheritance hierarchies and family trees.</p>
<p>But a hierarchy, strict or otherwise, is not the only way of
organizing elements in a program [<a href=
"#Hofstadter-">Hofstadter-</a>]:</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>A program which has such a structure in which there is no single
&quot;highest level&quot; ... is called a heterarchy (as distinguished from a
hierarchy).</p>
</blockquote>
</div>
<p>The property that distinguishes hierarchies from heterarchies is
that the former is acyclic whereas the latter contains cycles.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e37" id="d0e37"></a>Of Types and
Hierarchies</h2>
</div>
<p>When we look at a well-factored program, we see that the data
concepts have been abstracted according to their use more often
than their representation. Primitive data elements have been
grouped and reclassified as information with behavior [<a href=
"#Cardelli-">Cardelli-</a>]:</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>As soon as we start working in an untyped universe, we begin to
organize it in different ways for different purposes. Types arise
informally in any domain to categorize objects according to their
usage and behavior. The classification of objects in terms of the
purposes for which they are used eventually results in a more or
less well-defined type system. Types arise naturally, even starting
from untyped universes.</p>
</blockquote>
</div>
<p>In C++ we have many mechanisms for organizing our types. The two
most obvious are classes - which represent an explicitly named
concept made available to the compiler - and template type
parameters - where the concept of type is implicit according to
usage [<a href="#Henney2001">Henney2001</a>].</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e53" id="d0e53"></a>Types of
Subtyping</h2>
</div>
<p>Some hierarchies represent internal structural concerns: an
object hierarchy whose implementation is layered through
composition and forwarding, a function hierarchy where a task is
decomposed into smaller tasks that are decomposed in turn, and so
on. Type hierarchies, by contrast, reflect external usage
concerns.</p>
<p>The articulation of type and subtype concepts relates to the
four forms of polymorphism [<a href="#Cardelli-">Cardelli-</a>] -
inclusion, parametric, overloading, and coercion - and the five
forms of substitutability in C++ [<a href=
"#Henney2000a">Henney2000a</a>] - conversion, overloading,
derivation, mutability, and genericity.</p>
<p>There are examples of hierarchies where the structural and type
concerns are co-aligned. A class hierarchy, which has a tangible
structural dimension, can also be a type hierarchy, so that a
pointer to a derived class instance may be used where a pointer to
a base is declared. This example is the most commonly quoted form
of substitutability, but it is far from being the only one.</p>
<p>Because the number of implicit type conversions the compiler is
prepared to string together on your behalf is rather low - only one
foruser-defined conversions - subtype behavior across type
hierarchies based on this form of substitutability tends to be in
short hops. For instance, the following definitions describe a
relationship where a <span class="type">text</span> object is
expected a <span class="type">string</span> object may be provided,
and where a <span class="type">string</span> object is expected a
<span class="type">char *</span> may be provided:</p>
<pre class="programlisting">
class string 
{
public:
  string(const char *);
  ...
};

class text 
{
public:
  text(const string &amp;);
  ...
};
</pre>
<p>The following will compile happily:</p>
<pre class="programlisting">
text message = &quot;This will compile&quot;;
</pre>
<p>But the following will be thrown rudely back in your face:</p>
<pre class="programlisting">
void print(const text &amp;);
print(&quot;This won't compile&quot;);  // too many conversions required
</pre>
<p>When considering subtyping and genericity, an actual type must
support at least the features required for the template type
parameter, so the features of the named type used will inevitably
be a subtype of the required features. However, subtyping with
generics goes further than just this <span class=
"emphasis"><em>formal-actual</em></span> relationship, and iterator
categories provide a good example. Each category defines a
type<sup>[<a name="d0e97" href="#ftn.d0e97" id=
"d0e97">1</a>]</sup>, and the relationships between the categories
are in terms of subtyping: anything that can be considered a
<span class="emphasis"><em>random access iterator</em></span> will
also satisfy <span class="emphasis"><em>bidirectional
iterator</em></span> requirements, which in turn also satisfy
<span class="emphasis"><em>forward iterator</em></span>
requirements, which in turn satisfy both <span class=
"emphasis"><em>input iterator</em></span> and <span class=
"emphasis"><em>output iterator</em></span> requirements.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e116" id="d0e116"></a>Analysis of
Variance</h2>
</div>
<p>When looking at type hierarchies it is worth taking some time
out to understand how some of the properties of substitutability
come about.</p>
<p>Consider a base class and a derived class that is also a proper
subtype of the base (i.e., uses <span class="type">public</span>
inheritance from the base, overrides <span class=
"type">virtual</span> functions at least at their level of access
in the base, and ensures that any member functions that would
otherwise be blocked by members declared in the derived class are
made accessible through <span class="type">using</span>
declarations). What would you expect to find available in the
derived class's interface as compared to that of the base class?
You'd expect to find either the same set of members or more, but
not fewer. If you found fewer, this would break substitutability
because you could not use a derived where a base was expected. So
although you would have a class hierarchy, it would not be a type
hierarchy.</p>
<p>This means that the type interface, considered as a set of
operations, is <span class="emphasis"><em>contravariant</em></span>
with subtyping: as you descend the hierarchy, narrowing the
possible object types you can operate on, the set of operations
varies in the opposite direction (i.e., becomes wider). You can
also see this with generic types: a pointer, which is the model for
random access iterators, supports the same operations as an input
iterator, plus many more.</p>
<p>Zooming in on the interface, what about the substitutability
with respect to individual operations? As you descend the hierarchy
narrowing the possible object types, you also narrow the possible
behavior resulting from an operation call. This means that possible
results also narrow. In C++, if a virtual function's return type is
a pointer or reference, then it can be overridden with a more
derived return type. Thus the return type can be <span class=
"emphasis"><em>covariant</em></span> with subtyping: as you descend
the hierarchy, the result type also descends. As an example,
consider a simple factory scenario, where an interface class has a
Factory Method [<a href="#Gamma-et-al">Gamma-et-al</a>] that offers
the creation of instances of a product hierarchy:</p>
<pre class="programlisting">
class product 
{
  ...
};

class factory 
{
public:
  virtual product *create() const = 0;
  ...
};
</pre>
<p>Covariance allows us to capture more accurately the constraint
that a specific factory implementation returns a specific product,
as opposed to any arbitrary product:</p>
<pre class="programlisting">
class concrete_product : public product 
{
  ...
};

class concrete_factory
        : public factory 
{
public:
  virtual concrete_product *create() const 
  {
    return new concrete_product;
  }
  ...
};
</pre>
<p>Covariant return types make sense when it is likely that a user
will be accessing the feature through the derived type as opposed
to the base. This is not often the case, especially for a factory
that is intended to abstract concrete details, but it serves to
highlight the public advertisement of the constraint. Either way,
it is perfectly type-safe because any code written against the
<tt class="classname">factory</tt> interface:</p>
<pre class="programlisting">
product *example(const factory *creator) 
{
  return creator-&gt;create();
}
</pre>
<p>is still valid if we reconsider it in terms of <tt class=
"classname">concrete_factory</tt>:</p>
<pre class="programlisting">
product *example(const concrete_factory *creator) 
{
  return creator-&gt;create();
}
</pre>
<p>And, if this is all there is to writing factories for such
products, we can generalize the concrete factory code by mixing two
forms of polymorphism, inheritance and templates:</p>
<pre class="programlisting">
template&lt;typename concrete_product&gt;
class concrete_factory
    : public factory 
{
public:
  virtual concrete_product *create() const 
  {
    return new concrete_product;
  }
  ...
};
</pre>
<p>Any transgression of type safety - if <tt class=
"classname">concrete_product</tt> is not descended from <tt class=
"classname">product</tt> - will be picked up at compile time.</p>
<p>Covariance also applies to other results, such as <tt class=
"function">throw</tt> specs: an overridden <tt class=
"function">virtual</tt> function must declare the same <tt class=
"function">throw</tt> spec or a more restrictive one than the
function it is overriding. So, a virtual function that does not
have a <tt class="function">throw</tt> spec can be overridden by
one that does, a <tt class="function">virtual</tt> function that
declares an empty <tt class="function">throw</tt> spec can only be
overridden by one that also has an empty <tt class=
"function">throw</tt> spec, and a <tt class="function">virtual</tt>
function that promises only to <tt class="function">throw</tt> a
base exception type can be overridden by one that promises to
<tt class="function">throw</tt> the same, a descendant, or
nothing.</p>
<p>What about arguments? Does it make sense to have covariant
arguments? There is only one circumstance in which it is safe, and
C++ does not qualify for it: if a language supports <tt class=
"classname">out</tt> arguments that can be used only for results.
C++ <tt class="function">const</tt> reference arguments can be
considered in arguments and non-<tt class="function">const</tt>
reference arguments can be considered <tt class=
"function">inout</tt> arguments. Any argument that is effectively
<tt class="function">inout</tt> must be <span class=
"emphasis"><em>invariant</em></span> to be type safe. It is
feasible for in arguments to be contravariant, but this would
greatly complicate C++'s already subtle overloading rules, so the
rule is that all arguments remain invariant with subtyping. Some
languages attempt to support some covariance with in arguments -
this is the general case in Eiffel and is present only for array
passing in Java and C#, where argument signatures themselves are
not permitted to be covariant - but these are basically type system
hacks that require significant extra support, typically involving
runtime checks.</p>
<p>Covariance and contravariance are not just about declared types;
they are more generally about behavior. The promise of behavior for
an operation at supertype level must remain the same or be
strengthened and become narrower with subtyping. For example, is
the following a valid implementation of <tt class=
"classname">factory</tt>?</p>
<pre class="programlisting">
class null_factory
  : public factory 
{
public:
  virtual concrete_product *create() const 
  {
    return 0;
  }
  ...
};
</pre>
<p>It depends on what the expected result of <tt class=
"function">factory::create</tt> was promised as. If the promised
result at the base class level were simply &quot;returns a <tt class=
"function">delete</tt>-able pointer,&quot; then this permits null
pointers. Code written (correctly) against such an interface would
cater to this assumption:</p>
<pre class="programlisting">
void consume(product &amp;);
void example(const factory *creator) 
{
  std::auto_ptr&lt;product&gt; ptr(creator-&gt;create());
  if(ptr.get())
    consume(*ptr);
}
</pre>
<p>And so <tt class="function">null_factory::create</tt> could be
seen to be a valid specialization of <tt class=
"function">factory::create</tt> in this case because the behavior
is covariant, i.e., narrower and more specific than that of the
base.</p>
<p>However, if the promised result at the base class level were
specified as &quot;returns a non-null <tt class=
"function">delete</tt>-able pointer,&quot; <tt class=
"classname">null_factory</tt> would break code that worked to this
spec:</p>
<pre class="programlisting">
void consume(product &amp;);
void example(const factory *creator) 
{
  std::auto_ptr&lt;product&gt; ptr(creator-&gt;create());
  consume(*ptr);
}
</pre>
<p>And so <tt class="classname">null_factory</tt> would not be
substitutable for <tt class="classname">factory</tt>, and therefore
not a subtype.</p>
<p>You can also see the covariant promise in action with iterator
types: For an input or output iterator, there is no guarantee that
<tt class="computeroutput">a == b</tt> implies <tt class=
"computeroutput">++a = ++b</tt>, but for a forward <tt class=
"classname">iterator</tt> - and subtypes - the behavioral promise
is strengthened and this guarantee exists. Conversely, requirements
placed on callers of functions follow contravariance.</p>
<p>If you are familiar with <span class="emphasis"><em>design by
contract</em></span> [<a href="#Meyer">Meyer</a>], you may
recognize this as the strengthening of postconditions and weakening
of preconditions with inheritance. This variance in design by
contract is simply a different expression of the substitutability
principle and can be derived from it directly.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e291" id="d0e291"></a>Of Types and
Heterarchies</h2>
</div>
<p>Although you want to avoid cycles in your compile-time
dependency graph or between threads synchronizing on common
resources, there are occasions when heterarchies provide a more
appropriate structuring scheme than hierarchies. A function
heterarchy is expressed through recursion - either simple recursion
when a function calls itself or mutual recursion where another
called function calls the original caller. A bidirectional
relationship between objects can be considered an object
heterarchy. At any point in the execution, which object is
considered to be the top-level one depends on the action and
context. This is often the case with inversions of control flow
such as event notification callbacks.</p>
<p>In a hierarchy there is a unique concept of up and down -
imagine yourself anywhere in a hierarchical structure; there is a
strong sense of what is above you and what is below, and a strong
separation. In a heterarchy there is no such gravity - imagine
yourself in a heterarchy, looking &quot;up&quot; or &quot;down&quot; you can see
yourself.</p>
<p>Function recursion and cyclic object relationships are examples
of structural heterarchies, but what of type heterarchies? The
simplest example of type substitutability with a cycle is between
<span class="type">int</span> and <span class="type">double</span>:
one can be substituted where the other is expected. Granted,
<span class="type">double</span> to <span class="type">int</span>
is lossy, undesirable, and accompanied by a warning on most
compilers, but it does indeed form a type heterarchy. Similarly, if
a string class supports both a conversion to and from <span class=
"type">const char *</span> (the former being ill advised, but
nonetheless common), it too forms a cyclic substitutability
relationship.</p>
<p>However, these two examples are cautionary rather than
exemplary, and neither of them involves everyone's favorite class
relationship, inheritance.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e317" id="d0e317"></a>Touch
Base</h2>
</div>
<p>Imagine that you have customized the new and delete operators
for a class:</p>
<pre class="programlisting">
class workpiece 
{
public:
  static void *operator new(std::size_t);
  static void operator delete(void *, std::size_t);
  ...
private:
  ...
  static allocation heap;
};
</pre>
<p>Assume that allocation is a class that actually provides the
appropriate allocation intelligence - optimization for speed,
instrumentation for debugging, etc. - and can allocate objects of a
size fixed on its initialization and deallocate objects that it
allocated:</p>
<pre class="programlisting">
class allocation 
{
public:
  allocation(std::size_t, const std::type_info &amp;);
  void *allocate();
  void deallocate(void *);
  ...
};
</pre>
<p>Its correct use would be:</p>
<pre class="programlisting">
allocation workpiece::heap(
  sizeof(workpiece), typeid(workpiece));

void *workpiece::operator new(
                std::size_t size) 
{
  return size == sizeof(workpiece) ?
                heap.allocate() :
                ::operator new(size);
}

void workpiece::operator delete(
                void *ptr, std::size_t size) 
{
  if(size == sizeof(workpiece))
    heap.deallocate(ptr);
  else
    ::operator delete(ptr);
}
</pre>
<p>The <tt class="varname">size</tt> checks are important because
<tt class="function">new</tt> and <tt class="function">delete</tt>
are, by default, inherited and consequently may be used on a class
whose size does not equal that of the base. The code above ensures
that <tt class="classname">heap</tt> is used only for the intended
size and all other allocations and deallocations are rerouted to
the global operators.</p>
<p>If you intend to use <tt class="classname">allocation</tt> for
the same purpose in any other classes, it would be nice to somehow
factor out the code above as a mix-in class so that each class that
wanted these services would simply inherit from the mix-in.
Something like the following:</p>
<pre class="programlisting">
class allocated {
public:
  static void *operator new(std::size_t);
  static void operator delete(
                 void *, std::size_t);
  ...
private:
  ...
  static allocation heap;
};

class workpiece : public allocated {
  ...
};
</pre>
<p>Except not. All classes derived from <tt class=
"classname">allocated</tt> will share the same <tt class=
"classname">static heap</tt>:</p>
<pre class="programlisting">
class command : public allocated {
  ...
};
</pre>
<p>A <tt class="classname">command</tt> may not have the same size
as a <tt class="classname">workpiece</tt> and will certainly not
have the same type, so not only is <tt class="classname">heap</tt>
shared but it also becomes impossible to initialize or use
correctly, as the places marked ??? in the following code
indicate:</p>
<pre class="programlisting">
allocation allocated::heap(
  sizeof(???), typeid(???));

void *allocated::operator new(
                 std::size_t size) 
{
  return size == sizeof(???) ?
                 heap.allocate() :
                 ::operator new(size);
}

void allocated::operator delete(
                void *ptr,std::size_t size) 
{
  if(size == sizeof(???))
    heap.deallocate(ptr);
  else
    ::operator delete(ptr);
}
</pre>
<p>Even attempting to factor out the constant <tt class=
"function">sizeof</tt> expression will not solve the problem. It
serves only to highlight it more sharply.</p>
<p>Essentially the problem is that the mix-in cannot be made fully
independent of any derived class: there is a lingering dependency
on the name and size of the derived class. This creates a cycle
that can be broken by treating the downward dependency as a
parameter of variation, and therefore something to template
[<a href="#Coplien1999">Coplien1999</a>]:</p>
<pre class="programlisting">
template&lt;typename derived&gt;
class allocated 
{
public:
  static void *operator new(std::size_t);
  static void operator delete(
  void *, std::size_t);
  ...
private:
  ...
  static allocation heap;
};
</pre>
<p>Given this, the implementation code can now get at the name and
size of the type:</p>
<pre class="programlisting">
template&lt;typename derived&gt;
allocation allocated&lt;derived&gt;::heap(
  sizeof(derived), typeid(derived));

template&lt;typename derived&gt;
void *allocated&lt;derived&gt;::operator new(
                          std::size_t size) 
{
  return size == sizeof(derived) ?
               heap.allocate() :
               ::operator new(size);
}

template&lt;typename derived&gt;
void allocated&lt;derived&gt;::operator delete(
                 void *ptr, std::size_t size) 
{
  if(size == sizeof(derived))
    heap.deallocate(ptr);
  else
    ::operator delete(ptr);
}
</pre>
<p>The last piece falls into place with the mixing-in itself:</p>
<pre class="programlisting">
class workpiece : public allocated&lt;workpiece&gt;
{
  ...
};

class command : public allocated&lt;command&gt; {
  ...
};
</pre>
<p>Now the derived class inherits from a class that knows about it,
but without any hardwired coupling that prevents its use as a
general solution. Each parameterization of <tt class=
"classname">allocated</tt> results in a distinct type with its own
code and data, which is exactly what was required.</p>
<p>This is the increasingly well-known <span class=
"emphasis"><em>Self-Parameterized Base Class</em></span> or
<span class="emphasis"><em>Curiously Recurring Template</em></span>
pattern - the latter being an evocative description of its
recognition [<a href="#Coplien1995">Coplien1995</a>] and the former
being a more appropriate contemporary name based on its
structure.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e412" id="d0e412"></a>In Good
Shape</h2>
</div>
<p>The <tt class="classname">allocated</tt> class template
demonstrates an example of heterarchical structure involving class
relationships. However, it is not a type heterarchy because no
useful properties of type, except for <tt class=
"function">typeid</tt> and <tt class="function">sizeof</tt>, are
used: it steadfastly avoids dealing with objects.</p>
<p>Consider a simple shape hierarchy, with the usual suspects
<tt class="classname">ellipse</tt> and <tt class=
"classname">rectangle</tt>. It makes sense to be able to copy such
objects polymorphically by cloning them:</p>
<pre class="programlisting">
class shape 
{
public:
  virtual shape *clone() const = 0;
  ...
};

class ellipse : public shape 
{
public:
  explicit ellipse(const ellipse &amp;);
  virtual shape *clone() const {
    return new ellipse(*this);
  }
  ...
};

class rectangle : public shape 
{
public:
  explicit rectangle(const rectangle &amp;);
  virtual shape *clone() const {
    return new rectangle(*this);
  }
  ...
};
</pre>
<p>There are a couple of observations to make on this:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Cloning is effectively a reflexive <span class=
"emphasis"><em>Factory Method</em></span>, where the product and
factory are of the same class.</p>
</li>
<li>
<p>The <tt class="function">explicit</tt> copy constructor means
that although <tt class="classname">ellipse</tt> and <tt class=
"classname">rectangle</tt> support explicit copying - as seen in
<tt class="function">clone</tt> - the general case of passing and
returning them by copy is not supported, i.e. the identity
conversion is disabled. shape objects are heap-bound and live in a
class hierarchy, rather than being valuebased objects for which
casual copying makes sense.</p>
</li>
<li>
<p>The implementations of <tt class="function">ellipse::clone</tt>
and <tt class="function">rectangle::clone</tt> are suspiciously
similar, differing only in the class to which they refer.</p>
</li>
</ul>
</div>
<p>It would be nice to factor out the common source structure,
except that it is the structure as opposed to the verbatim code
that needs factoring out. Again, there is a cyclic type dependency,
and this time more entrenched because of object creation and copy
construction. And again, a <span class=
"emphasis"><em>Self-Parameterized Base Class</em></span> offers a
way to break the cycle [<a href="#Henney1999">Henney1999</a>]:</p>
<pre class="programlisting">
class shape 
{
public:
  virtual shape *clone() const = 0;
  ...
};

template&lt;typename derived, typename base&gt;
class cloner : public virtual base 
{
public:
  virtual base *clone() const 
  {
    return new derived(
      static_cast&lt;const derived &amp;&gt;(*this));
  }
  ...
};

class ellipse : public cloner&lt;ellipse, shape&gt; 
{
  ...
};

class rectangle : public cloner&lt;rectangle, shape&gt; 
{
  ...
};
</pre>
<p>There are a few observations to make on this solution:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>To reiterate a property of heterarchies: you really can see
yourself if you look down.</p>
</li>
<li>
<p>An attempt to parameterize <tt class="classname">cloner</tt>
with a non-derived class will cause a compile-time error because
the derived class will not be substitutable for the base in the
code.</p>
</li>
<li>
<p>If you consider cloning to be a reflexive version of
<span class="emphasis"><em>Factory Method</em></span>, this
solution mirrors the templated <tt class=
"classname">concrete_factory</tt> in a reflexive way: in each case,
the product is the first template parameter.</p>
</li>
<li>
<p>Another adaptive template technique, <span class=
"emphasis"><em>Parameterized Inheritance</em></span>, is used to
define the appropriate base class.</p>
</li>
<li>
<p>Inheritance uses a <tt class="function">virtual</tt> base class
to accommodate other applications of this reflexive mix-in style,
but without introducing repeated inheritance issues.</p>
</li>
</ul>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e512" id=
"d0e512"></a>Conclusion</h2>
</div>
<p>A template technique that is becoming increasingly common has
been taken and explored within the conceptual framework of
substitutability. From its early sightings [<a href=
"#Barton-">Barton-</a>] and subsequent exploration [<a href=
"#Coplien1995">Coplien1995</a>] to the present day [<a href=
"#Henney2000b">Henney2000b</a>, <a href="#Kreft-">Kreft-</a>], the
<span class="emphasis"><em>Self-Parameterized Base
Class</em></span> pattern has found increased applicability in
expressing cyclic type relationship problems once they have been
recognized as such.</p>
<p>There are many techniques that combine two main forms of
generalization - templates and inheritance - and a number of them
have been used in this article. However, a <span class=
"emphasis"><em>Self-Parameterized Base Class</em></span> has the
distinction that it unifies the forms under the heading of
substitutability but not of hierarchy.</p>
<div class="sidebar">
<p>This article was originally published on the C/C++ Users Journal
C++ Experts Forum in August 2001 at <a href=
"http://www.cuj.com/experts/documents/s=7992/cujcexp1908Henney/"
target=
"_top">http://www.cuj.com/experts/documents/s=7992/cujcexp1908Henney/</a></p>
<p>Thanks to Kevlin for allowing us to reprint it.</p>
</div>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e544" id="d0e544"></a>Notes and
References</h2>
</div>
<div class="bibliomixed"><a name="Jackson" id="Jackson"></a>
<p class="bibliomixed">[Jackson] Michael Jackson. <span class=
"citetitle"><i class="citetitle">Software Requirements &amp;
Specifications: A Lexicon of Practice, Principles and
Prejudices</i></span> (Addison-Wesley, 1995).</p>
</div>
<div class="bibliomixed"><a name="Hofstadter-" id=
"Hofstadter-"></a>
<p class="bibliomixed">[Hofstadter-] Douglas R. Hofstadter.
G&ouml;del, Escher, Bach: <span class="citetitle"><i class=
"citetitle">An Eternal Golden Braid</i></span> (Penguin, 1979).</p>
</div>
<div class="bibliomixed"><a name="Cardelli-" id="Cardelli-"></a>
<p class="bibliomixed">[Cardelli-] Luca Cardelli and Peter Wegner.
&quot;On Understanding Types, Data Abstraction, and Polymorphism,&quot;
<span class="citetitle"><i class="citetitle">Computing
Surveys</i></span>, December 1985.</p>
</div>
<div class="bibliomixed"><a name="Henney2001" id="Henney2001"></a>
<p class="bibliomixed">[Henney2001] Kevlin Henney. &quot;From Mechanism
to Method: Good Qualifications,&quot; <span class="citetitle"><i class=
"citetitle">C/C++ Users Journal C++ Experts Forum</i></span>,
January 2001, <span class="bibliomisc"><a href=
"http://www.cuj.com/experts/1901/henney.htm" target=
"_top">http://www.cuj.com/experts/1901/henney.htm</a></span></p>
</div>
<div class="bibliomixed"><a name="Henney2000a" id=
"Henney2000a"></a>
<p class="bibliomixed">[Henney2000a] Kevlin Henney. &quot;From Mechanism
to Method: Substitutability&quot; <span class="citetitle"><i class=
"citetitle">C++ Report</i></span>, May 2000, also available from
<span class="bibliomisc"><a href="http://www.curbralan.com" target=
"_top">http://www.curbralan.com</a></span></p>
</div>
<div class="bibliomixed"><a name="Gamma-et-al" id=
"Gamma-et-al"></a>
<p class="bibliomixed">[Gamma-et-al] Erich Gamma, Richard Helm,
Ralph Johnson, and John Vlissides. <span class=
"citetitle"><i class="citetitle">Design Patterns: Elements of
Reusable Object-Oriented Software</i></span> (Addison-Wesley,
1995).</p>
</div>
<div class="bibliomixed"><a name="Meyer" id="Meyer"></a>
<p class="bibliomixed">[Meyer] Bertrand Meyer. <span class=
"citetitle"><i class="citetitle">Object-Oriented Software
Construction</i></span>, 2nd edition (Prentice Hall, 1997).</p>
</div>
<div class="bibliomixed"><a name="Coplien1999" id=
"Coplien1999"></a>
<p class="bibliomixed">[Coplien1999] James O. Coplien. <span class=
"citetitle"><i class="citetitle">Multi-Paradigm Design for
C++</i></span> (Addison-Wesley, 1999).</p>
</div>
<div class="bibliomixed"><a name="Coplien1995" id=
"Coplien1995"></a>
<p class="bibliomixed">[Coplien1995] 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="Henney1999" id="Henney1999"></a>
<p class="bibliomixed">[Henney1999] Kevlin Henney. &quot;Clone Alone,&quot;
<span class="citetitle"><i class="citetitle">Overload
33</i></span>, August 1999.</p>
</div>
<div class="bibliomixed"><a name="Barton-" id="Barton-"></a>
<p class="bibliomixed">[Barton-] John J. Barton and Lee R. Nackman.
<span class="citetitle"><i class="citetitle">Scientific and
Engineering C++: An Introduction with Advanced Techniques and
Examples</i></span> (Addison-Wesley, 1994).</p>
</div>
<div class="bibliomixed"><a name="Henney2000b" id=
"Henney2000b"></a>
<p class="bibliomixed">[Henney2000b] Kevlin Henney. Email
correspondence with Angelika Langer, July 2000, <span class=
"bibliomisc"><a href=
"http://www.langer.camelot.de/IOStreams/forum.htm" target=
"_top">http://www.langer.camelot.de/IOStreams/forum.htm</a></span></p>
</div>
<div class="bibliomixed"><a name="Kreft-" id="Kreft-"></a>
<p class="bibliomixed">[Kreft-] Klaus Kreft and Angelika Langer.
&quot;Effective C++ Standard Library: Curiously Recurring Manipulators,&quot;
<span class="citetitle"><i class="citetitle">C/C++ Users Journal
C++ Experts Forum</i></span>, June 2001, <span class=
"bibliomisc"><a href="http://www.cuj.com/experts/1906/langer.htm"
target=
"_top">http://www.cuj.com/experts/1906/langer.htm</a></span></p>
</div>
</div>
<div class="footnotes"><br>
<hr class="c3" width="100">
<div class="footnote">
<p><sup>[<a name="ftn.d0e97" href="#d0e97" id=
"ftn.d0e97">1</a>]</sup> Note that these generic requirements-based
types are sometimes referred to as concepts. However, use of this
term is inadvisable because of its impressive accuracy without any
precision whatsoever: everything in software development can be
considered a concept, but only a few things can be considered
types. Generic requirements define - quite precisely - types.</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
