    <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/315</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 #59 - Feb 2004 + 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/c153/">59</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/c153-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c153+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 February 2004 21:55:34 +00:00 or Mon, 02 February 2004 21:55:34 +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>Further Qualifications</h3>
</div>
<p>Qualification is often used as a simple constraint on behavior.
For instance, a non-<tt class="computeroutput">const</tt> member
function cannot be executed on a <tt class=
"computeroutput">const</tt>-qualified object. In the general case,
a <tt class="computeroutput">const</tt>-qualified member function
can be used with both <tt class="computeroutput">const</tt>- and
non-<tt class="computeroutput">`const</tt> qualified objects; the
exception is when the function is also overloaded privately as
non-const. This exception highlights the other common use of
qualification to distinguish between two functions and two
different outcomes, although normally in a more substitutable
fashion (i.e., so that the non-<tt class=
"computeroutput">const</tt> version is effectively a subtype
specialization of the <tt class="computeroutput">const</tt> version
[<a href="#Henney2001a">Henney2001a</a>]).</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e48" id="d0e48"></a>Qualification,
Separation, and Unification</h2>
</div>
<p>You can see this kind of substitutability in action with
iterator access in the C++ Standard's container requirements:
non-<tt class="computeroutput">const</tt> container access yields
<tt class="computeroutput">iterator</tt>s whereas <tt class=
"computeroutput">const</tt> container access yields <tt class=
"computeroutput">const_iterator</tt>s, and, furthermore, an
<tt class="computeroutput">iterator</tt> may be used where a
<tt class="computeroutput">const_iterator</tt> is expected. In this
case, qualification-based separation leads to <tt class=
"computeroutput">iterator</tt> and <tt class=
"computeroutput">const_iterator</tt> types.</p>
<p>Qualification can also be used as a means for unification.
Consider an object that supports both reader locks and writer locks
for safe multithreaded access: so long as there are no writers,
multiple reader locks can be acquired and the owners can look at
the object without changing it (i.e., only const operations); the
owner of a writer lock has exclusive read-write access to an object
(i.e., both <tt class="computeroutput">const</tt> and
non-<tt class="computeroutput">const</tt> operations). Translating
these concepts directly into code suggests the following:</p>
<pre class="programlisting">
class table 
{
public:
  void lock() const;   // acquire lock for reading
  void lock();         // acquire lock for
                       // reading and writing
  void unlock() const; // release reader lock
  void unlock();       // release writer lock
  ...
};
</pre>
<p>The acquisition and release of the lock now reflects the
permissions of the calling context:</p>
<pre class="programlisting">
void reader_example(const table *target) 
{
  target-&gt;lock(); // acquires lock for reading
  ...
  target-&gt;unlock(); // releases reader lock
}
void writer_example(table *target) 
{
  target-&gt;lock(); // acquires lock for
  // reading and writing
  ...
  target-&gt;unlock(); // releases writer lock
}
</pre>
<p>Such access is made exception safe by introducing an
acquisition-release object [<a href=
"#Stroustrup1997">Stroustrup1997</a>, <a href=
"#Henney2000a">Henney2000a</a>]:</p>
<pre class="programlisting">
template&lt;typename lockee_type&gt;
class locker 
{
public:
  locker(lockee_type &amp;target) : target(target) 
  {
    target.lock(); 
  }
  ~locker() 
  {
    target.unlock();
  }
private:
  locker(const locker &amp;);
  locker &amp;operator=(const locker &amp;);
  lockee_type &amp;target;
};
</pre>
<p>What's neat about this design is that only a single <tt class=
"computeroutput">locker</tt> template is needed to cater for both
<tt class="computeroutput">const</tt> and non-<tt class=
"computeroutput">const</tt> variants:</p>
<pre class="programlisting">
void reader_example(const table *target) 
{
  locker&lt;const table&gt; guard(*target);
                     // acquires reader lock
  ...
}
void writer_example(table *target) 
{
  locker&lt;table&gt; guard(*target);
              // acquires writer lock
  ...
}
</pre>
<p>Code that is written to be both scope constrained and <tt class=
"computeroutput">const</tt> correct will avoid pessimistic locking
scenarios, where a lock is acquired for longer than is strictly
necessary or the lock acquired is too strong for the required
access.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e119" id="d0e119"></a>Write-Back
Proxies</h2>
</div>
<p>Consider a slightly different scenario: objects that can be
loaded on demand into memory and, when changed, written back. It is
safe to assume that non-<tt class="computeroutput">const</tt>
operations will cause change and <tt class=
"computeroutput">const</tt> operations won't, and that users will
perform predominantly <tt class="computeroutput">const</tt> or
non-<tt class="computeroutput">const</tt> operations on a given
object in a particular role:</p>
<pre class="programlisting">
class datapoint 
{
public:
  double upper_bound() const;
  void upper_bound(double);
  double lower_bound() const;
  void lower_bound(double);
  ...
};
</pre>
<p>The only problem is that the objects are independent of your
loading and saving framework. They do not contain convenient
features that would make this problem trivial to resolve, such as a
<tt class="computeroutput">dirty</tt> flag to show when they've
been modified. A simplistic, verbose, and errorprone approach would
be to save or not in response to each call:</p>
<pre class="programlisting">
void view(const datapoint *target) 
{
  double = target-&gt;upper_bound();
  // no save required
  ...
}
void manipulate(datapoint *target,
                double new_upper_bound) 
{
  ...
  target-&gt;upper_bound(new_upper_bound);
  // save required
  save(target); // assume a non-member
  // save for target
}
</pre>
<p>This code also assumes that the object has been preloaded into
memory.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e147" id="d0e147"></a>Custom
Proxies</h2>
</div>
<p>The standard solution to such problems is to manage the level of
indirection with a proxy object [<a href=
"#Buschmann-">Buschmann-</a>, <a href=
"#Gamma-et-al">Gamma-et-al</a>]. A custom proxy, written to handle
each of the member functions individually, can be written to
encapsulate both the lazy loading and the save policy:</p>
<pre class="programlisting">
class datapoint_view 
{
public:
  double upper_bound() const 
  {
    if(!target)
      load();
    return target-&gt;upper_bound();
  }
  void upper_bound(double new_upper_bound) 
  {
    if(!target)
      load();
    target-&gt;upper_bound(new_upper_bound);
    save();
  }
  ...
private:
  void load() const;
  void save();
  mutable datapoint *target;  // null when
                              // not loaded
  persistence_key target_key; // used by load
};
</pre>
<p>Clients now work in terms of <tt class=
"computeroutput">datapoint_view</tt> instead of <tt class=
"computeroutput">datapoint</tt>. Although conventional, proxies and
targets do not necessarily have to inherit from a common base
class, in this case, unless the <tt class=
"computeroutput">datapoint</tt> author included an interface class
for another reason, it may not even be possible to perform such
inheritance without further adaptation.</p>
<p>However, although simple in many ways, this design is tediously
repetitive. Each function follows a similar flow: load if not yet
loaded, forward call, and then optionally a call to save state. It
is also hardwired to a single target type. A generic solution would
allow arbitrary data types to be managed in the same way. Smart
pointers offer the most common idiom for such generic managed
indirection.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e173" id="d0e173"></a>Smart
References</h2>
</div>
<p>Consider first a simple case for a generic loading-and-saving
smart pointer: working with built-in types or user-defined value
types that, like built-ins, are manipulated only in terms of
operators. The focus of operations is, therefore, on the
dereferenced value. Another proxy variant, a smart reference,
allows basic reads and writes to be distinguished:</p>
<pre class="programlisting">
template&lt;typename target_type&gt;
class loading_ptr {
public:
  ...
  class reference 
  {
  public:
    explicit reference(const loading_ptr *that)
      : that(that) {}
    operator target_type() const 
    {
      return *that-&gt;target;
    }
    reference &amp;operator=(const target_type &amp;rhs) 
    {
      *that-&gt;target = rhs;
      that-&gt;save();
      return *this;
    }
  private:
    const loading_ptr *that;
  };

  reference operator*() const 
  {
    if(!target)
      load();
    return reference(this);
  }
  ...
private:
  ...
  friend class reference;
  void load() const;
  void save() const;
  mutable target_type *target; // null when
  // not loaded
  persistence_key target_key;  // used by load
};
</pre>
<p>A smart reference cannot be a perfect match for a real reference
[<a href="#Meyers">Meyers</a>], but such a limitation on
transparency is true to a greater or lesser extent of any kind of
proxy. For instance, the UDC (user-defined conversion) operator
means that the result of dereferencing a <tt class=
"computeroutput">loading_ptr</tt> is an rvalue rather than an
lvalue. The disadvantage of the UDC as it stands is that it uses up
the allotment of one userdefined conversion. A little generic
thinking gets round this problem:</p>
<pre class="programlisting">
template&lt;typename target_type&gt;
class loading_ptr 
{
public:
  ...
  class reference 
  {
  public:
    ...
    template&lt;typename result_type&gt;
    operator result_type() const 
    {
      return *that-&gt;target;
    }
    ...
  private:
    loading_ptr *that;
  };
  ...
};
</pre>
<p>The downside is that this permissive conversion can create some
fresh new ambiguities: the templated UDC now eagerly matching all
possibilities unless explicitly disambiguated. You have to choose
between evils according to which least affects your code - I guess
that you probably don't need reminding that the world is not a
perfect place.</p>
<p>Almost all the overloadable operators can be overloaded to make
working with the smart reference reflect the natural use of its
target type more accurately. This is fine for built-in types and
like-minded value classes, but not for targets with named members:
for them, <tt class="computeroutput">operator-&gt;</tt> must be
overloaded.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e197" id="d0e197"></a>Bracketing
Smart Pointers</h2>
</div>
<p>But over-eagerness to implement <tt class=
"computeroutput">operator-&gt;</tt> will lead you straight into a
brick wall:</p>
<pre class="programlisting">
template&lt;typename target_type&gt;
class loading_ptr {
public:
  ...
  target_type *operator-&gt;() const 
  {
    if(!target)
      load();
    return target;
  }
  ...
};
</pre>
<p>Sure, the object may have been successfully loaded into memory,
but when and how will it be saved? The save needs to occur after
the pointer has been returned and a member dereferenced through it
- in other words, outside the body of <tt class=
"computeroutput">operator-&gt;</tt> over which you have
control.</p>
<p>It would appear that you can never have too many proxies: the
solution is to return a smart pointer from <tt class=
"computeroutput">loading_ptr</tt>'s <tt class=
"computeroutput">operator-&gt;</tt> and have its destructor perform
the save:</p>
<pre class="programlisting">
template&lt;typename target_type&gt;
class loading_ptr 
{
public:
  ...
  class pointer 
  {
  public:
    explicit pointer(const loading_ptr *that)
      : that(that), accessed(false) 
    {
    }
    target_type *operator-&gt;() const {
      accessed = true;
      return that-&gt;target;
    }
    ~pointer() 
    {
      if(accessed)
      that-&gt;save();
    }
  private:
    const loading_ptr *that;
    bool accessed;
  };
  pointer operator-&gt;() const 
  {
    if(!target)
      load();
    return pointer(this);
  }
  ...
private:
  friend class pointer;
  ...
};
</pre>
<p>What makes this idiom tick is that <tt class=
"computeroutput">operator-&gt;</tt> chains: if the result of
<tt class="computeroutput">operator-&gt;</tt> also supports an
<tt class="computeroutput">operator-&gt;</tt>, this latter operator
is called automatically, and so on until the result chain reaches a
real pointer. What makes this idiom tock is the binding of a
temporary object's lifetime to the end of the surrounding full
expression. So, when used in a simple expression, the load is
performed in the first <tt class=
"computeroutput">operator-&gt;</tt>, which returns a temporary
object used to access the members - either function or data - of
the underlying target, and the save is performed by the destruction
of the temporary object at the end of the expression:</p>
<pre class="programlisting">
void manipulate(loading_ptr&lt;datapoint&gt; target,
                double new_upper_bound) 
{
  ...
  target-&gt;upper_bound(new_upper_bound);
  // ^load if necessary ^save
}
</pre>
<p>This versatile bracketing technique has acquired various names
over time: locking pointer in the context of thread synchronization
[<a href="#Henney1996">Henney1996</a>], call wrappers [<a href=
"#Stroustrup2000">Stroustrup2000</a>], and execute-around pointers
[<a href="#Henney2000b">Henney2000b</a>].</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e249" id="d0e249"></a>The Depths of
Qualification</h2>
</div>
<p>But before you get too distracted or overwhelmed by the many
levels and kinds of proxy you have at your disposal, remember that
part of the design requirement was to distinguish between
<tt class="computeroutput">const</tt> and non-<tt class=
"computeroutput">const</tt> usage. The code currently assumes the
non-<tt class="computeroutput">const</tt> case (i.e., always save).
How can you distinguish a <tt class="computeroutput">const</tt>
target?</p>
<p>A common, but alas incorrect, solution to this problem is to
reflect the qualification of the smart pointer in the qualification
of the result:</p>
<pre class="programlisting">
template&lt;typename target_type&gt;
class loading_ptr 
{
public:
  ...
  pointer operator-&gt;() 
  {
    if(!target)
      load();
    return pointer(this);
  }
  const target_type *operator-&gt;() const 
  {
    if(!target)
      load();
    return target; // return actual pointer as
                   // no save needed
  }
  ...
};
</pre>
<p>There are certainly designs in which you would want such deep
qualification, but this isn't one of them. For a composition
relationship through a pointer, where an object pointed to by
another is considered a part of a whole, qualification should run
deeply, just as it does for a data member by value. For
association, where the relationship represented is not whole-part,
qualification should be shallow, which is the case for many
indirection-based relationships. Making it deep arises from
confusion - albeit commonplace - over levels of indirection: the
qualification of your smart pointer relates to whether or not you
can affect the smart pointer itself, not its referand.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e272" id="d0e272"></a>Many Roads
Lead to Rome</h2>
</div>
<p>There are two user roles with respect to target usage for the
writeback proxy: a read-only role, which we can equate to accessing
a const target, and a write-mostly role, which we can equate to
accessing a non-const target and typically accessing non-<tt class=
"computeroutput">const</tt> members. If deep qualification were the
only solution to this kind of problem, iterators to const
containers would be stuck on the starting blocks. The good news is
that not only is there a solution, there are many solutions, each
with a different set of tradeoffs.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e280" id="d0e280"></a>Separately
Qualified Types</h2>
</div>
<p>Taking a leaf straight out of the standard library, the iterator
model can be used as the inspiration for a pair of class
templates:</p>
<pre class="programlisting">
template&lt;typename target_type&gt;
class loading_ptr 
{
public:
  ...
  class pointer 
  {
    ...
  };
  pointer operator-&gt;() const 
  {
    if(!target)
      load();
    return pointer(this);
  }
  ...
};

template&lt;typename target_type&gt;
class const_loading_ptr 
{
public:
  const_loading_ptr(
            const loading_ptr&lt;target_type&gt; &amp;);
  ...
  const target_type *operator-&gt;() const 
  {
    if(!target)
      load();
    return target;
  }
  ...
};
</pre>
<p>Note the converting constructor from a <tt class=
"computeroutput">loading_ptr</tt> to a <tt class=
"computeroutput">const_loading_ptr</tt>. This could also be
supported by introducing a UDC to a <tt class=
"computeroutput">const_loading_ptr</tt> in the <tt class=
"computeroutput">loading_ptr</tt> template. Either way, a
<tt class="computeroutput">loading_ptr</tt> is substitutable for a
<tt class="computeroutput">const_loading_ptr</tt>. Note also that
there is potentially a certain amount of duplicated code. A simple
alternative that offers both substitutability and factoring of
common code is to introduce an inheritance relationship:</p>
<pre class="programlisting">
template&lt;typename target_type&gt;
class const_loading_ptr 
{
  ...
};
template&lt;typename target_type&gt;
class loading_ptr
  : public const_loading_ptr&lt;target_type&gt; 
{
  ...
};
</pre>
<p>Some members will be fully &quot;specialized&quot; and &quot;overridden&quot; in the
derived class (i.e., <tt class="computeroutput">operator-&gt;</tt>
will be provided in <tt class="computeroutput">loading_ptr</tt> and
will block the one in <tt class=
"computeroutput">const_loading_ptr</tt> from view). This is
compile-time polymorphism rather than run-time polymorphism - there
are no virtual functions in sight, nor should there be.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e320" id="d0e320"></a>Qualified
Type Specialization</h2>
</div>
<p>The <tt class="computeroutput">const_loading_ptr</tt> solution
is OK except that it leaves us with two different type names. This
means that for an arbitrary type <tt class="computeroutput">T</tt>,
which may or may not be <tt class="computeroutput">const</tt>
qualified, you cannot simply write <tt class=
"computeroutput">loading_ptr&lt;T&gt;</tt> and expect it to do the
right thing (i.e., <tt class="computeroutput">loading_ptr&lt;const
datapoint&gt;</tt> is not equivalent to <tt class=
"computeroutput">const_loading_ptr&lt;datapoint&gt;</tt>). Template
specialization with respect to qualification offers a
simplification [<a href="#Henney2001b">Henney2001b</a>]:</p>
<pre class="programlisting">
// primary class template
template&lt;typename target_type&gt;
class loading_ptr 
{
public:
  ...
  class pointer 
  {
    ...
  };
  pointer operator-&gt;() const 
  {
    if(!target)
      load();
    return pointer(this);
  }
  ...
};
// partial specialization
template&lt;typename target_type&gt;
class loading_ptr&lt;const target_type&gt; 
{
public:
  loading_ptr(
        const loading_ptr&lt;target_type&gt; &amp;);
  ...
  const target_type *operator-&gt;() const 
  {
    if(!target)
      load();
    return target;
  }
  ...
};
</pre>
<p>This means that one template name, <tt class=
"computeroutput">loading_ptr</tt>, covers both cases, with
<tt class="computeroutput">loading_ptr&lt;datapoint&gt;</tt>
corresponding to the primary template definition and <tt class=
"computeroutput">loading_ptr&lt;const datapoint&gt;</tt>
corresponding to the partial specialization. Inheritance can again
be used to provide substitutability and cure the common code:</p>
<pre class="programlisting">
// forward declare primary class template
template&lt;typename target_type&gt;
class loading_ptr;
// partial specialization
template&lt;typename target_type&gt;
class loading_ptr&lt;const target_type&gt; 
{
  ...
};
template&lt;typename target_type&gt;
class loading_ptr
  : public loading_ptr&lt;const target_type&gt; 
{
  ...
};
</pre>
<p>It is worth pointing out that not all compilers support
specialization with respect to qualification.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e363" id="d0e363"></a>Explicit
Qualification Check</h2>
</div>
<p>There are only a few parts of the <tt class=
"computeroutput">loading_ptr</tt> template that need to be
different between the const and non-const variant. Instead of
partially specializing the whole class template, why not just do so
for the affected functions? This is an elegant and economic idea;
unfortunately it also won't work: the C++ Standard currently
disallows partial specialization of function templates. You can
overload or fully specialize a function template, but alas neither
of these options is directly suitable for the member functions in
this particular problem.</p>
<p>However, the effect of <tt class="computeroutput">const</tt>
partial specialization can, to a limited degree, be emulated.
Instead of focusing on the <tt class=
"computeroutput">loading_ptr</tt>, focus on the result of
<tt class="computeroutput">operator-&gt;</tt>. Return the pointer
proxy in each case and determine only in the destructor whether or
not a save is required.</p>
<p>Here is a brute force run-time type checked approach:</p>
<pre class="programlisting">
template&lt;typename target_type&gt;
loading_ptr&lt;target_type&gt;::pointer::~pointer() 
{
  if(accessed &amp;&amp;
       typeid(target_type *)
       != typeid(const target_type *))
    that-&gt;save();
}
</pre>
<p>Because <tt class="computeroutput">typeid</tt> ignores top-level
qualifiers, the code is phrased in terms of pointers. The trick
that allows the <tt class="computeroutput">const</tt>
discrimination to work is to recall that const qualifying something
that is already <tt class="computeroutput">const</tt> qualified has
no effect. However, this approach lacks both elegance and economy.
You can eliminate the run-time type check by introducing a
predicate:</p>
<pre class="programlisting">
template&lt;typename target_type&gt;
loading_ptr&lt;target_type&gt;::pointer::~pointer() 
{
  if(accessed &amp;&amp; !is_const(that-&gt;target))
    that-&gt;save();
}
</pre>
<p>Here, it is overloading with respect to const that allows the
predicate approach to work:</p>
<pre class="programlisting">
template&lt;typename type&gt;
bool is_const(type *) 
{
  return false;
}
template&lt;typename type&gt;
bool is_const(const type *) 
{
  return true;
}
</pre>
<p>If these functions are inlined - and your compiler is doing at
least a halfway decent job with inlining - there will be no
run-time overhead in this approach. Compile-time selection is the
territory of traits - a far more elegant approach:</p>
<pre class="programlisting">
template&lt;typename target_type&gt;
loading_ptr&lt;target_type&gt;::pointer::~pointer() 
{
  if(accessed &amp;&amp; !is_const&lt;target_type&gt;::value)
    that-&gt;save();
}
</pre>
<p>The following mono-trait class template uses <tt class=
"computeroutput">const</tt> partial specialization to make the
distinction:</p>
<pre class="programlisting">
template&lt;typename type&gt;
struct is_const 
{
  static const bool value = false;
};
template&lt;typename type&gt;
struct is_const&lt;const type&gt; 
{
  static const bool value = true;
};
</pre>
<p>This approach can also be made to work using <tt class=
"computeroutput">const</tt>-qualified pointers and partial
specialization [<a href="#Boost">Boost</a>] if your compiler does
not support direct <tt class="computeroutput">const</tt>
specialization.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e425" id="d0e425"></a>Qualified
Double Dispatch</h2>
</div>
<p>There is a way to have selection without explicit control flow
and to simulate the partial specialization of function templates.
Double dispatch allows you to select an action on an object
externally based on the type of the object. A family of functions
performs the selection on your behalf calling back on the object
you pass. This is normally described in terms of different classes
in a hierarchy and forms the basis of the conventional form of the
VISITOR pattern [<a href="#Gamma-et-al">Gamma-et-al</a>]. We can
also frame double dispatch in terms of qualification, which is
simply a different, more constrained form of subtyping.</p>
<p>Depending on the kind of extensibility you want in your design,
you can define your dispatch functions either outside or inside the
class. The following code uses class statics to retain some
consistency with the previous solutions:</p>
<pre class="programlisting">
template&lt;typename target_type&gt;
class loading_ptr {
public:
  ...
  class pointer 
  {
  public:
    ...
    ~pointer() 
    {
      if(accessed)
        save(that); // select appropriate
                    // save strategy
    }
  private:
    template&lt;typename save_type&gt;
    static void save(
         loading_ptr&lt;save_type&gt; *that) 
    {
      that-&gt;save();
    }
    template&lt;typename save_type&gt;
    static void save(
         loading_ptr&lt;const save_type&gt; *) 
    {
      // do nothing as no save is needed
    }
    loading_ptr *that;
    bool accessed;
  };
  ...
};
</pre>
<p>If overloading with respect to the full <tt class=
"computeroutput">loading_ptr</tt> type does not work for your
compiler, restructure the code so that you overload with respect to
the target pointer.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e442" id=
"d0e442"></a>Conclusion</h2>
</div>
<p>Overloading with respect to qualification combines with
templates to provide a valuable form of subtyping and
specialization. Whilst not all of the techniques demonstrated are
within reach of all compilers, there is enough overlap between
their applicability to allow you some implementation wriggle
room.</p>
<p>The <tt class="computeroutput">write-back</tt> proxy allows a
number of issues to be explored, although it is not intended to
demonstrate all that you would need in such a design. For instance,
matters of object lifetime and thread synchronization have been
glossed over. There is also an important assumption in the
applicability of the core design: if the non-<tt class=
"computeroutput">const</tt> access is not write mostly there will
be a lot of wasted saves. However, as C++ is currently defined
there is no way that a proxy can both be made generic and
distinguish on the qualification of the actual target member
accessed, so this is unfortunately a natural constraint.</p>
<div class="sidebar">
<p>This article was originally published on the C/C++ Users Journal
C++ Experts Forum in September 2001 at <a href=
"http://www.cuj.com/experts/documents/s=7991/cujcexp1909Henney/"
target=
"_top">http://www.cuj.com/experts/documents/s=7991/cujcexp1909Henney/</a></p>
<p>Thanks to Kevlin for allowing us to reprint it.</p>
</div>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e462" id="d0e462"></a>References</h2>
</div>
<div class="bibliomixed"><a name="Henney2001a" id=
"Henney2001a"></a>
<p class="bibliomixed">[Henney2001a] Kevlin Henney. &quot;From Mechanism
to Method: Good Qualifications,&quot; C/C++ Users Journal C++ Experts
Forum, January 2001, www.cuj.com/experts/1901/henney.htm</p>
</div>
<div class="bibliomixed"><a name="Stroustrup1997" id=
"Stroustrup1997"></a>
<p class="bibliomixed">[Stroustrup1997] Bjarne Stroustrup. C++
Programming Language, 3rd Edition (Addison-Wesley, 1997).</p>
</div>
<div class="bibliomixed"><a name="Henney2000a" id=
"Henney2000a"></a>
<p class="bibliomixed">[Henney2000a] Kevlin Henney. &quot;C++ Patterns:
Executing Around Sequences,&quot; EuroPLoP 2000, July 2000, also
available from www.curbralan.com</p>
</div>
<div class="bibliomixed"><a name="Buschmann-" id="Buschmann-"></a>
<p class="bibliomixed">[Buschmann-] Frank Buschmann, Regine
Meunier, Hans Rohnert, Peter Sommerlad, and Michael Stal.
Pattern-Oriented Software Architecture: A System of Patterns
(Wiley, 1996).</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. Design Patterns: Elements of
Reusable Object-Oriented Software (Addison-Wesley, 1995).</p>
</div>
<div class="bibliomixed"><a name="Meyers" id="Meyers"></a>
<p class="bibliomixed">[Meyers] Scott Meyers. More Effective C++:
35 New Ways to Improve Your Programs and Designs, (Addison-Wesley,
1996).</p>
</div>
<div class="bibliomixed"><a name="Henney1996" id="Henney1996"></a>
<p class="bibliomixed">[Henney1996] Kevlin Henney. &quot;C++ Advanced
Design Issues: Asynchronous C++,&quot; Visual Tools Developers' Academy
(Oxford, September 1996).</p>
</div>
<div class="bibliomixed"><a name="Stroustrup2000" id=
"Stroustrup2000"></a>
<p class="bibliomixed">[Stroustrup2000] Bjarne Stroustrup.
&quot;Wrapping C++ Member Function Calls,&quot; C++ Report, June 2000.</p>
</div>
<div class="bibliomixed"><a name="Henney2000b" id=
"Henney2000b"></a>
<p class="bibliomixed">[Henney2000b] Kevlin Henney. &quot;From Mechanism
to Method: Substitutability,&quot; C++ Report, May 2000, also available
from www.curbralan.com</p>
</div>
<div class="bibliomixed"><a name="Henney2001b" id=
"Henney2001b"></a>
<p class="bibliomixed">[Henney2001b] Kevlin Henney. &quot;From Mechanism
to Method: Distinctly Qualified,&quot; C/C++ Users Journal C++ Experts
Forum, May 2001, www.cuj.com/experts/1905/henney.htm</p>
</div>
<div class="bibliomixed"><a name="Boost" id="Boost"></a>
<p class="bibliomixed">[Boost] Boost library website,
www.boost.org</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
