    <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  :: The Policy Bridge Design Pattern</title>
        <link>https://members.accu.org/index.php/journals/1369</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 #79 - Jun 2007 + Programming Topics + Design of applications and programs</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/c224/">79</a>
                    (6)
<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/">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/c67/">Design</a>
                    (236)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c224-65-67/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c224+65+67/">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;The Policy Bridge Design Pattern</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 04 June 2007 11:59:00 +01:00 or Mon, 04 June 2007 11:59:00 +01:00</p>
<p><strong>Summary:</strong>&nbsp;Matthieu Gilson offers some thoughts on using a policy based mechanism to build efficient classes from loosely coupled
components.</p>
<p><strong>Body:</strong>&nbsp;<p>
The problem considered in this paper is not new and relates to generic
programming: how to build a class made of several 'components' that can
have various implementations where these components can communicate
with each other, while keeping the design of the components
independent? For instance, an object would consist of an update
mechanism plus a data structure, where both belong to a family of
various mechanisms and data structures (distinct mechanisms perform
distinct processes, etc.; thus some couples of mechanism-data are
compatible and others are not). </p>
<p> To be more precise, such components would be implemented in classes
(or similar entities) and use methods from other 'classes', while their
design is kept orthogonal. The introduction illustrates this problem
and then presents a solution using member function templates. </p>
<p> An alternative solution (so-called Policy Bridge) is then
presented, where the 'components' are implemented in policies
[<a href="#Alexandrescu01">Alexandrescu01</a>], [<a
 href="#VandevoordeJosuttis03">Vandevoorde/Josuttis03</a>] and the
pattern 'bridges'
them to construct an instantiated type. The term 'bridge' here refers
to the usual <tt class="code">Bridge</tt> pattern: the instantiated
type can be seen as an interface that inherits the functionality of all
the policies it is made of. The compatibility between the policies (for
instance checking the interface at a call of a function from another
policy) is checked at compile time. A common interface can be
implemented with the cost of a virtual function for each call. </p>
<p> So far, the functionality achieved by the policy bridge is similar
to the ones using member function templates and a brief comparison with
meta-functions is explored as well. The code may be heavier but in a
sense the design is more modular with policies. A combination of
policies with meta-functions, to bring more genericity to encode the
components, is then introduced. Policy-based visitors that enable
visiting of some of the policies involved in the construction of an
object via its interface. </p>
<p> A generic version of the policy bridge is then presented and the
automation of such a code for an arbitrary number of policies (using
macros from the preprocessor library of Boost [<a href="#Boost">Boost</a>]).
</p>
<p> The example code runs under g++ (3.4.4 and 4.02), Visual C++ (7.1
and 8), and Comeau. </p>
<h2> Introduction </h2>
<p> Let us play with neurons. Such objects can be abstracted
mathematically, with various features and mechanisms to determine their
activity: activation mechanism (their internal update method); synapses
to connect them; etc. In order to simulate a network made of various
types of neurons interconnected with various types of connections, and
keep the design as flexible as possible to be able to combine the
different mechanisms together at will. </p>
<p> Without even going as far as connecting neurons, a fair number of
design issues arise. Say we have a data structure which represents a
feature of one type of neuron: </p>
<pre class="programlisting">class Data1<br>{<br>public:<br>  Data1(double a) : a_(a) {}<br>  const double &amp; a() {return a_;}<br>protected:<br>  const double a_;<br>};  </pre>
<p> and an update mechanism to model the state of our neuron where the
update method uses the parameter a implemented in the data: </p>
<pre class="programlisting">class UpdateMech1<br>{<br>public:<br>  const double &amp; state() const {return state_;}<br>  UpdateMech1() : state_(0.) {}<br>  void update(double a) {state_ += a;}<br>protected:<br>  double state_;<br>};    </pre>
<p> Our neuron is somehow the 'merging' of both classes, and another
update method at the level of <tt class="code">Neuron1</tt> has to be
declared so as to link the parameter of <tt class="code">UpdateMech1::update</tt>
with <tt class="code">Data1::a()</tt>: </p>
<pre class="programlisting">class Neuron1<br>  : public Data1<br>  , public UpdateMech1<br>{<br>public:<br>  Neuron1(double a) : Data1(a) {}<br>  void update() {UpdateMech1::update(Data1::a());}<br>};<br>    </pre>
<p> To make it more generic for various data and mechanisms (say we
have <tt class="code">Data1</tt> and <tt class="code">Data2</tt>, <tt
 class="code">UpdateMech1</tt> and <tt class="code">UpdateMech2</tt>),
we can templatise the features and mechanisms: </p>
<pre class="programlisting">template &lt;class Data, class UpdateMech&gt;<br>class Neuron<br>  : public Data<br>  , public UpdateMech<br>{<br>  ...<br>  void update() {UpdateMech::update(Data::a());}<br>};  </pre>
<p> Yet, all of the <tt class="code">DataX</tt> would now require a
method <tt class="code">a</tt> and all the <tt class="code">UpdateMechX</tt>
would require an update method with a double as parameter, which is not
flexible. The alternative using abstract base classes for both the
family of the data classes (<tt class="code">DataBase</tt>) and the
family of the update mechanisms (<tt class="code">UpdateMechBase</tt>),
while <tt class="code">Neuron</tt> would hold one member variable for
each family, would face similar limitations: </p>
<pre class="programlisting">class Neuron<br>{<br>  ...<br>  void update() {u_.update(d_.a());}<br>  DataBase * d_;<br>  UpdateMechBase * u_;<br>};   </pre>
<p> Indeed, the interface <tt class="code">DataBase</tt> should have a
pure virtual method <tt class="code">a</tt>: </p>
<pre class="programlisting">struct DataBase<br>{<br>  virtual const double &amp; a() = 0;<br>};  </pre>
<p> and this would cause the interface to be rigid (even more than with
the template version): it could be necessary for other update
mechanisms to get a non-constant <tt class="code">a</tt>, which does
not fit this method <tt class="code">a</tt>; if some more variables
are needed by only a particular <tt class="code">UpdateMechX</tt>, the
whole common interface still has to be modified; etc. Actually, the
family of the data classes needs no common interface here, provided
that for each combination with a specific <tt class="code">UpdateMechX</tt>,
the latter knows how to call the variable it needs. On the contrary,
the machinery implemented in <tt class="code">DataX</tt> and <tt
 class="code">UpdateMechX</tt> and their way to communicate with each
other should remain as unconstrained as possible (in terms of
constructors, etc.), only <tt class="code">Neuron</tt> would need a
common interface in the end. </p>
<p> Speed could be another reason to discard this alternative choice,
since the template version does not require virtual functions, and thus
the internal mechanisms remain fast (only function calls). </p>
<p> The former version of <tt class="code">Neuron</tt> can be modified
to make the combinations between the <tt class="code">DataX</tt> and
the <tt class="code">UpdateMechX</tt> more flexible. An option is to
change <tt class="code">UpdateMechX</tt> into class templates where <tt
 class="code">DataX</tt> is the template argument of <tt class="code">UpdateMechX</tt>,
and to derive them from the classes <tt class="code">DataX</tt>, as
shown in Listing 1.<br>
</p>
<table class="sidebartable">

    <tr>
      <td style="vertical-align: top;">
      <pre class="programlisting"> class Data1<br> {<br>   ...<br>   const &amp; double a();<br> }; </pre>
      <pre class="programlisting"> template &lt;class Data&gt;<br> class UpdateMech1<br>   : public Data<br> {<br>   ...<br>   void update() {state_ += Data::a();}<br> };<br></pre>
      <pre class="programlisting"> template &lt;class UpdateMech&gt;<br> class Neuron<br>   : public UpdateMech<br> { ... }; </pre>
      <pre class="programlisting"> Neuron&lt;UpdateMech1&lt;Data1&gt; &gt; nrn1;<br> nrn1.update();<br></pre>
      </td>
    </tr>
    <tr>
      <td class="title">Listing 1
      </td>
    </tr>

</table>
<p> This way, we can define various update mechanisms and various data
classes, and combine them together. The <tt class="code">Data</tt>
family and the <tt class="code">UpdateMech</tt> family are kept
somehow independent in terms of design: basically, <tt class="code">UpdateMech1</tt>
only requires to know the name of the method <tt class="code">a</tt>
implemented in all of the <tt class="code">DataX</tt> to be combined
with <tt class="code">UpdateMech1</tt>; type checks require that <tt
 class="code">a</tt> returns a type convertible into <tt class="code">const
double</tt>. </p>
<p> The construction <tt class="code">Neuron&lt;UpdateMech&lt;Data&gt;
&gt;</tt> still has quite strong limitations, in the sense that <tt
 class="code">Data</tt> and <tt class="code">UpdateMech</tt> are no
longer on the same level in the derivation tree above <tt class="code">Neuron</tt>.
Imagine that one of the data classes also needs to use a method that
belongs to the family of the <tt class="code">UpdateMechX</tt>. Or
imagine there are not just one update mechanism but two (e.g. a
learning mechanism <tt class="code">PlasticityMech</tt> in addition to
the <tt class="code">UpdateMech</tt> for some specific neurons), and
they both would have to use something from the <tt class="code">Data</tt>
class family; both would derive from <tt class="code">Data</tt>, and <tt
 class="code">Neuron</tt> would derive from both, so the derivation
from <tt class="code">Data</tt> must be virtual, as shown in Listing 2.<br>
</p>
<table class="sidebartable">

    <tr>
      <td style="vertical-align: top;">
      <pre class="programlisting">class Data1;<br></pre>
      <pre class="programlisting">template &lt;class Data&gt;<br>class UpdateMech1<br>  : virtual public Data<br>{ ... };<br></pre>
      <pre class="programlisting">template &lt;class Data&gt;<br>class PlasticityMech1<br>  : virtual public Data<br>{ ... };    </pre>
      <pre class="programlisting">template &lt;class UpdateMech, class PlasticityMech&gt;<br>class Neuron<br>  : public UpdateMech<br>  , public PlasticityMech<br>{ ... };<br></pre>
      </td>
    </tr>
    <tr>
      <td class="title">Listing 2
      </td>
    </tr>

</table>
<p> Since there was no virtual machinery before, this may imply costs.
But even if we would not care, there is a last reason to seek for
another solution: there may eventually be a need to implement
mechanisms with 'new' interactions that we cannot really predict at
this stage; and any further change would possibly mess up our beautiful
(but rigid) derivation tree. </p>
<p> Let us go back to thinking of our design and what we wanted of it.
The key idea here is that <tt class="code">UpdateMech1</tt> requires
that <tt class="code">Neuron</tt> has a method <tt class="code">a</tt>
that is used by <tt class="code">UpdateMech1</tt>, but the fact that <tt
 class="code">Neuron</tt> inherits <tt class="code">a</tt> from <tt
 class="code">Data1</tt> does not matter to <tt class="code">UpdateMech1</tt>.
Other mechanisms may have 'requirements', which makes mechanisms
compatible or not (to be detected at compile time). They would need to
be all at the 'same level' in the derivation tree, i.e. any mechanism
or feature is equally likely to need something in another one. In other
words, we want a design likely to combine any compatible update and
data 'classes' in a flexible way and thus define a neuron out of them;
these mechanisms can communicate together while they are kept as
'orthogonal' as possible (they only know the name of the methods
belonging to other mechanisms they need to call); and as few virtual
functions as possible should be involved in the internal machinery
(within <tt class="code">Neuron</tt>), to try to keep fast
computation. </p>
<p> One solution can be to use member function templates (in the
classes that define the features or mechanisms) for the methods that
require a feature from outside their scope (Listing 3) and to call <tt
 class="code">update_impl</tt> from the class <tt class="code">Neuron</tt>
with <tt class="code">*this</tt> as an argument (Listing 4).<br>
</p>
<table class="sidebartable">

    <tr>
      <td style="vertical-align: top;">
      <pre class="programlisting">class UpdateMech1<br>{<br>  ...<br>protected:<br>  template &lt;class TypeImpl&gt;<br>  void update_impl(TypeImpl &amp; obj) {state_ += obj.a_impl();}<br>};    </pre>
      <pre class="programlisting">class Data1<br>{<br>  friend class UpdateMech1;<br>protected:<br>  const double &amp; a_impl();<br>  ...<br>};<br></pre>
      </td>
    </tr>
    <tr>
      <td  class="title">Listing 3
      </td>
    </tr>

</table>
<p><br>
</p>
<table class="sidebartable">

    <tr>
      <td style="vertical-align: top;">
      <pre class="programlisting">template &lt;class Data, class UpdateMech&gt;<br>class Neuron<br>  : public Data<br>  , public UpdateMech<br>{<br>  ...<br>  void update() {UpdateMech::update_impl(*this)}<br>};<br></pre>
      </td>
    </tr>
    <tr>
      <td class="title">Listing 4
      </td>
    </tr>

</table>
<p> Note that <tt class="code">UpdateMech1</tt> has to be a friend of <tt
 class="code">Data1</tt> if <tt class="code">a_impl</tt> is protected.
We would need to add similar declarations for any other mechanism to be
combined with <tt class="code">Data1</tt>, or define all the methods
as <tt class="code">public</tt> in the features and mechanisms.
Another slight drawback is that the calls to the member function
templates must come from <tt class="code">Neuron</tt>, which means
that having a pointer to one of the mechanisms (such as <tt
 class="code">UpdateMech</tt>) is not sufficient to call the update
method if it is a template method (we still would need to pass the <tt
 class="code">Neuron</tt> object as an argument). </p>
<p> In the end, this solution is valid and would be suitable for our
requirements. Yet, we will now consider an alternative design, which
brings further possibilities. The trade-off is mainly the increase in
complexity in the design. </p>
<h2> Details of the design </h2>
<p> The purpose is still to allow any mechanism to call 'directly' any
method from another 'mechanism' from which <tt class="code">Neuron</tt>
derives (via the class <tt class="code">Neuron</tt>). To give a rough
idea, instead of the function template nested in the mechanism class (<tt
 class="code">UpdateMech1::update_impl&lt;class TypeImpl&gt;(TypeImpl
&amp;)</tt>), the whole class <tt class="code">UpdateMech1</tt> is now
a class template with a non template function (<tt class="code">UpdateMech1&lt;class
TypeImpl&gt;::update_impl()</tt>). This idea has something to do with
the well-known trick used together with curiously recurring pattern
(CRTP [<a href="#Alexandrescu01">Alexandrescu01</a>], [<a
 href="#VandevoordeJosuttis03">Vandevoorde/Josuttis03</a>]): </p>
<pre class="programlisting">template &lt;class TypeImpl&gt;<br>class UpdateMech<br>{<br>  void update_impl()<br>  {<br>    state_ += static_cast&lt;TypeImpl &amp;&gt;(*this).a();<br>  }<br>};   </pre>
<p> Defined this way, <tt class="code">UpdateMech</tt> can be seen as
a policy [<a href="#Alexandrescu01">Alexandrescu01</a>], [<a
 href="#VandevoordeJosuttis03">Vandevoorde/Josuttis03</a>] on the
implemented
type <tt class="code">TypeImpl</tt> with the template argument <tt
 class="code">Neuron</tt>. It allows us to call the method <tt
 class="code">a</tt> that <tt class="code">Neuron</tt> inherits from <tt
 class="code">Data</tt> by means of <tt class="code">static_cast</tt>,
which converts the self-reference <tt class="code">*this</tt> to the
instantiated policy object back to <tt class="code">Neuron</tt>. </p>
<p> This use of policies is somewhat different from [<a
 href="#Alexandrescu01">Alexandrescu01</a>]: a
usual example is the pointer class <tt class="code">SmartPtr</tt>
defined on a type <tt class="code">T</tt> (to make it shorter than <tt
 class="code">TypeImpl</tt>) and some properties of the pointers can be
implemented by policies. For instance, let us build a policy to count
the references of the pointed element (Listing 5) and the smart pointer
class template is then as shown in Listing 6.<br>
</p>
<table class="sidebartable">

    <tr>
      <td style="vertical-align: top;">
      <pre class="programlisting"> template &lt;class T&gt;<br> class CountRef<br> {<br> private:<br>   int * count_;<br> protected:<br>   void CountPolicy() {count_ = new int();<br>      *count_ = 1;}<br>   bool release()<br>   {<br>     if (!--*count_) {<br>       delete count_; count_ = NULL; return true;<br>     } else return false;<br>   }<br>   T clone(T &amp; t) {++*count_; return t;}<br>   ...<br> };<br></pre>
      </td>
    </tr>
    <tr>
      <td class="title">Listing 5
      </td>
    </tr>

</table>
<p><br>
</p>
<table class="sidebartable">

    <tr>
      <td style="vertical-align: top;">
      <pre class="programlisting">template &lt;class T<br>  , template &lt;class&gt; CountPolicy&gt;<br>class SmartPtr<br>  : public CountPolicy&lt;T&gt;<br>{<br>public:<br>  SmartPtr(T * ptr) : CountPolicy&lt;T&gt;(), <br>     ptr_(ptr) {}<br>  ~SmartPtr()<br>  {<br>    if (CountPolicy&lt;T&gt;::release())<br>      delete ptr_;<br>  }<br>  ...<br>protected:<br>  T * ptr_;<br>};<br></pre>
      </td>
    </tr>
    <tr>
      <td class="title">Listing 6
      </td>
    </tr>

</table>
<p> The policy <tt class="code">CountRef</tt> here is a mechanism that
uses the type <tt class="code">T</tt>, and <tt class="code">SmartPtr</tt>
uses <tt class="code">T</tt> and <tt class="code">CountRef</tt>, so
there is no recursion in the design. However, we want to build <tt
 class="code">Neuron</tt> which uses <tt class="code">DataPolicy&lt;Neuron&gt;</tt>
and <tt class="code">UpdatePolicy&lt;Neuron&gt;</tt>. </p>
<p> First, we rewrite the mechanisms <tt class="code">Data1</tt> and <tt
 class="code">UpdateMech1</tt> as policies (see Listing 7).<br>
</p>
<table class="sidebartable">

    <tr>
      <td style="vertical-align: top;">
      <pre class="programlisting">template &lt;class TypeImpl&gt;<br>class Data1<br>{<br>protected:<br>  typedef double VarTypeInit;<br>  Data1(VarTypeInit a) : a_(a) {}<br>  const double &amp; a_impl() {return a_;} <br>private:<br>  const double a_;<br>};    </pre>
      <pre class="programlisting">template &lt;class TypeImpl&gt;<br>class UpdateMech1<br>{<br>public:<br>  const double &amp; state() const {return state_;}<br>protected:<br>  UpdateMech1() : state_(0.) {}<br>  void update_impl()<br>  {<br>    state_ += <br>        static_cast&lt;TypeImpl &amp;&gt;(*this).a_impl();<br>  }<br>private:<br>  double state_;<br>};<br></pre>
      </td>
    </tr>
    <tr>
      <td class="title">Listing 7
      </td>
    </tr>

</table>
<p> Note that the <tt class="code">typdedef</tt><tt class="code">VarTypeInit</tt>
was added in <tt class="code">Data1</tt> to define the type of the
parameter required to initialise this policy. </p>
<p> Then the <tt class="code">Neuron</tt> pattern straightforwardly
combines these two policies, i.e. it derives from the two policies
applied on itself (see Listing 8).<br>
</p>
<table class="sidebartable">

    <tr>
      <td style="vertical-align: top;">
      <pre class="programlisting">template &lt;template &lt;class&gt; class DataPolicy<br>  , template &lt;class&gt; class UpdatePolicy&gt;<br>class  Neuron<br>  : public DataPolicy&lt;Neuron&lt;DataPolicy,<br>     UpdatePolicy&gt; &gt;<br>  , public UpdatePolicy&lt;Neuron&lt;DataPolicy,<br>     UpdatePolicy&gt; &gt;<br>{<br>  friend class DataPolicy&lt;Neuron&gt;;<br>  friend class UpdatePolicy&lt;Neuron&gt;;<br><br>public:<br>  Neuron(DataPolicy::VarTypeInit a)<br>    : DataPolicy&lt;Neuron&gt;(a)<br>    , UpdatePolicy&lt;Neuron&gt;()<br>  {}<br>  const double &amp; a() {<br>     return DataPolicy&lt;Neuron&gt;::a_impl();}<br>  void update()<br>     {UpdatePolicy&lt;Neuron&gt;::update_impl();}<br>};<br></pre>
      </td>
    </tr>
    <tr>
      <td class="title">Listing 8
      </td>
    </tr>

</table>
<p> The requirements for the policy any <tt class="code">DataPolicyX</tt>
is to define a type <tt class="code">VarTypeInit</tt> to be used in
its constructor and have a method <tt class="code">a_impl</tt> that
returns a type that can be converted to <tt class="code">const double
&amp;</tt>. Likewise for <tt class="code">UpdatePolicyX</tt> which
must have a method <tt class="code">update_impl</tt> (no return type
is required). </p>
<p> Now, we can simply define <tt class="code">Neuron1</tt> as a
combination of <tt class="code">Data1</tt> and <tt class="code">UpdateMech1</tt>:
</p>
<pre class="programlisting">typedef Neuron&lt;Data1, UpdateMech1&gt; Neuron1;<br></pre>
<p> The policies can communicate together, via the casting back to <tt
 class="code">TypeImpl</tt>. Indeed, thanks to the friend declarations
in <tt class="code">Neuron</tt>, each policy can access to the members
of <tt class="code">Neuron</tt>, which inherits the protected members
of all the policies. Note also that the public function members of the
policies and of <tt class="code">Neuron</tt> will be public for <tt
 class="code">TypeImpl</tt>. What is private within a policy cannot be
accessed by other policies, to keep safe variables (e.g. via protected
accessors). An alternative option is to use protected derivation
instead of the public one here in the design of <tt class="code">Neuron</tt>,
in order to prevent public members of the policies from being
accessible from <tt class="code">TypeImpl</tt>. </p>
<p> Now, we define two new policies <tt class="code">Data2</tt> and <tt
 class="code">UpdateMech2</tt> (respectively in the same family as <tt
 class="code">Data1</tt> and <tt class="code">UpdateMech1</tt>), but
the data <tt class="code">a_</tt> is no longer constant in <tt
 class="code">Data2</tt>, and the update method of <tt class="code">UpdateMech2</tt>
changes its value. Furthermore, <tt class="code">Data2</tt> has a <tt
 class="code">learning</tt> method which modifies its variable <tt
 class="code">a_</tt> according to the variable <tt class="code">state_</tt>
(see Listing 9).<br>
</p>
<table class="sidebartable">

    <tr>
      <td style="vertical-align: top;">
      <pre class="programlisting">template &lt;class TypeImpl&gt;<br>class Data2<br>{<br>protected:<br>  typedef double VarTypeInit;<br>  Data2(VarTypeInit a) : a_(a) {}<br>  double &amp; a_impl() {return a_;}<br>  void learning()<br>  {<br>    if (static_cast&lt;TypeImpl &amp;&gt;<br>        (*this).state_impl()&gt;10) --a_;<br>  }<br>private:<br>  double a_;<br>};<br></pre>
      <pre class="programlisting">template &lt;class TypeImpl&gt;<br>class UpdateMech2<br>{<br>public:<br>  const double &amp; state() const {return state_;}<br>protected:<br>  UpdateMech2() : state_(0.) {} <br>  void update_impl()<br>  {<br>    state_ += <br>        ++static_cast&lt;TypeImpl &amp;&gt;(*this).a_impl();<br>  }<br>private:<br>  double state_;<br>};<br></pre>
      </td>
    </tr>
    <tr>
      <td class="title">Listing 9
      </td>
    </tr>

</table>
<p> These two policies are 'compatible' in the sense that the update
policy modifies the data <tt class="code">a_</tt>, which is not
constant as a return type of <tt class="code">a_impl</tt> in <tt
 class="code">Data2</tt> and the type <tt class="code">Neuron2</tt>
defined by: </p>
<pre class="programlisting">typedef Neuron&lt;Data2, UpdateMech2&gt; Neuron2;<br>Neuron2 nrn2;<br>nrn2.update();<br></pre>
<p> is thus 'legal'. So is the combination between <tt class="code">Data2</tt>
and <tt class="code">UpdateMech1</tt>. </p>
<p> However, the class <tt class="code">Neuron3</tt> defined here: </p>
<pre class="programlisting">typedef Neuron&lt;Data1, UpdateMech2&gt; Neuron3;<br>Neuron3 nrn3;<br>nrn3.update();    </pre>
<p> is ill-defined because the implemented <tt class="code">update_impl</tt>
method of <tt class="code">UpdateMech2</tt> tries to modify the data <tt
 class="code">a_</tt> of <tt class="code">Data1</tt> which is
constant, and the method cannot be called on an object of this type.
Such an incompatibility is detected at compile time (the member
function templates described achieve same functionalities). Depending
on the compiler, the incompatibility is detected when defining the type
<tt class="code">Neuron&lt;Data1, UpdateMech2&gt;</tt> (g++) or when
calling the method <tt class="code">update</tt> (VC8). </p>
<p> The term bridged objects here refers to instantiated types using a
policy bridge. If we want to design an interface for all the neurons to
access <tt class="code">a_impl</tt> (with <tt class="code">const
double &amp;</tt> as common return type) and <tt class="code">update_impl</tt>,
we can add another derivation to <tt class="code">Neuron</tt> with
pure virtual methods. For example for <tt class="code">update_impl</tt>:
</p>
<pre class="programlisting">struct InterfaceBase<br>{<br>  virtual void update() = 0;<br>};   </pre>
<p> which provides the common method update that has to be defined in a
derived class. We can either do it in <tt class="code">Neuron</tt> (or
in a derived class if needed). Defining it in <tt class="code">Neuron</tt>
saves some code: </p>
<pre class="programlisting">template &lt;...&gt; class Neuron : public InterfaceBase,<br>    ...;<br>void Neuron&lt;...&gt;::update() {<br>  UpdatePolicy&lt;Neuron&gt;::update_impl();}</pre>
<p>but then the order of the policies in the list of the template
arguments is then fixed. On the contrary, in a dedicated derivation
(instead of a <tt class="code">typedef</tt> like <tt class="code">Neuron1</tt>
above), the order of the template argument list can be changed at will:
</p>
<pre class="programlisting">class Neuron4<br>  : public Neuron&lt;Data1, UpdateMech1&gt;<br>  , public InterfaceBase;    </pre>
<p> and we can also imagine combining more than two policies to define
neurons. The latter option would keep the design more generic (see the
generic version <tt class="code">PolicyBridgeN</tt> of <tt
 class="code">Neuron</tt>), with no member function but the
constructor. Yet, the same code would be duplicated in all the derived
classes. Note that such an interface also allows us to store neurons in
standard containers. </p>
<p> Now, to implement a special interface for the 'learning' neurons,
we just have to derive the suitable policy (only <tt class="code">Data2</tt>
here, but we can imagine more) from another abstract base class with a
pure virtual method called <tt class="code">learning</tt>: </p>
<pre class="programlisting">struct Interface1<br>{<br>  Interface1() {list_learning_nrn.push_back(this);}<br>  virtual void learning() = 0;<br>  std::list&lt;Interface1 * const&gt;<br>  list_learning_neurons;<br>};<br>template &lt;class TypeImpl&gt;<br>  class Data2 : public Interface1 {...};</pre>
<p>Thus, learning neurons can be handled and updated specifically (for
their learning mechanisms only) separately from the rest of the neurons
(useful when the distinct processes happen at distinct times for
example): </p>
<pre class="programlisting">for(std::list&lt;Interface1 * const&gt;::iterator i = <br>      Interface1::list_learning_neurons.begin();<br>    i != Interface1::list_learning_neurons.end();<br>    ++i)<br>  (*i)-&gt;learning();  </pre>
<p> This polymorphic feature only uses the derivation from an abstract
base class and the cost is the one of a virtual function call at run
time. Note that any bridged class (whatever the bridge like <tt
 class="code">Neuron</tt>) can actually share the same interface, and
thus can be handled together as shown here. An alternative solution
could be to use the variant pattern and suitable visitors [<a
 href="#Boost">Boost</a>],
[<a href="#Tiny">Tiny</a>]. </p>
<h2> Further considerations </h2>
<p> So far, apart from the dedicated interfaces, this design based on
policies has functionality comparable with member function templates.
Another difference is that the body of <tt class="code">Neuron</tt>
does not have to be changed for a new mechanism with a method that
requires internal communication (like when adding <tt class="code">Data2::learning</tt>).
We indeed do not need to change <tt class="code">Neuron</tt> with
policy, whereas we would have to define in the body of <tt class="code">Neuron</tt>
a call for <tt class="code">Data2::learning&lt;TypeImpl&gt;</tt> when
using member function templates. </p>
<p> Note that the computation speed is equivalent for the two options,
since all the internal mechanisms are based on function calls (no
virtual function, only the use of an interface involves a virtual
function call). </p>
<p> Further refinement can be obtained using meta-functions (that
implement polymorphism at compile-time). So far, we only considered
policies with one sole template argument, which is eventually the type
of the bridged object (<tt class="code">TypeImpl</tt>). Say we want to
parametrise some of the policies with more template parameters. For
example, the <tt class="code">learning</tt> in data class <tt
 class="code">Data2</tt> would depend on an algorithm embedded in a
class, thus we need to add an extra template parameter for <tt
 class="code">Data2</tt> (and not <tt class="code">Data1</tt>): </p>
<pre class="programlisting">template&lt;class TypeImpl, class Algo&gt; class Data2;    </pre>
<p> We can no longer use the policy bridge to build neurons with
distinct algorithms because the template signature of <tt class="code">Data2</tt>
is different now (one template parameter in the original design of the
policy bridge <tt class="code">Neuron</tt>). Meta-functions can help
here: </p>
<pre class="programlisting">template&lt;class Algo&gt;<br>struct GetData2<br>{<br>  template &lt;class TypeImpl&gt;<br>  struct apply<br>  { <br>    typedef Data1&lt;TypeImpl, Algo&gt; Type;<br>  };<br>};    </pre>
<p> With this design, <tt class="code">TypeImpl</tt> will be provided
by the bridge, and all the other template parameters can be set via <tt
 class="code">GetData2</tt> (with suitable defaulting if needed). The
policy bridge then becomes as shown in Listing 10.<br>
</p>
<table class="sidebartable">

    <tr>
      <td style="vertical-align: top;">
      <pre class="programlisting">template &lt;class GetData, class GetUpdateMech&gt;<br>class Neuron<br>  : public GetData::template<br>      apply&lt;Neuron&lt;GetData, GetUpdateMech&gt; &gt;::Type<br>    , public GetUpdateMech::template<br>        apply&lt;Neuron&lt;GetData, GetUpdateMech&gt; &gt;::Type<br>{<br>  typedef typename GetData::<br>    template apply&lt;Neuron&gt;::Type InstData;<br>  typedef typename GetUpdateMech<br>    ::template apply&lt;Neuron&gt;::Type <br>   InstUpdateMech ;<br><br>  friend InstData;<br>  friend InstUpdateMech;<br><br>protected:<br>  Neuron(InstData::VarTypeInit <br>         var_init)<br>    : InstData(var_init)<br>    , InstUpdateMech()<br>  {}<br>};<br></pre>
      </td>
    </tr>
    <tr>
      <td class="title">Listing 10
      </td>
    </tr>

</table>
<p> Note that the instantiated policy <tt class="code">GetData::template
apply&lt;Neuron&gt;::Type</tt> was renamed into <tt class="code">InstData</tt>
using <tt class="code">typedef</tt> (likewise for <tt class="code">InstUpdateMech</tt>)
in order to simplify the code. A neuron type can thus be simply
created: </p>
<pre class="programlisting">typedef Neuron&lt;GetData2&lt;Algo1&gt;, <br>  GetUpdateMech2&gt; Neuron5;    </pre>
<p> Non-template classes with member function templates can be used
with usual visitors because they have a plain type. We adapt here the
processing using basic visitors [<a href="#Alexandrescu01">Alexandrescu01</a>]
(with an abstract base
class <tt class="code">VisitorBase</tt>) to be able to visit the
policies which a bridged object is made of: </p>
<pre class="programlisting">class VisitorBase<br>{<br>  virtual ~VisitorBase() {}<br>};<br>template &lt;class T&gt;<br>class Visitor<br>{<br>  virtual void visit(T &amp;) = 0;<br>};<br></pre>
<p> In particular, such a visitor must have the same behaviour for all
the types <tt class="code">T = Policy1&lt;...&gt;</tt>, for a given <tt
 class="code">Policy1</tt>. We thus need a tag to identify each policy,
which is common to all the instantiated types related to the same
policy, and a solution is to use <tt class="code">Policy&lt;void&gt;</tt>
because it will never be used in any bridged object. A particular
visitor for <tt class="code">Data1</tt> and <tt class="code">Data2</tt>
would be implemented: </p>
<pre class="programlisting">class DataVisitor<br>  : public VisitorBase<br>  , public Visitor&lt;Data1&lt;void&gt; &gt;<br>  , public Visitor&lt;Data2&lt;void, void&gt; &gt;<br>{<br>  void visit(Data1&lt;void&gt; &amp; d) {...}<br>  visit(Data2&lt;void, void&gt; &amp; d) {...}<br>};  </pre>
<p> Now, a method <tt class="code">apply_vis(VisitorBase &amp; vis)</tt>
has to be defined at the interface level (pure virtual method), and
defined at the same level as <tt class="code">update</tt> to call the
method in the policy (here in <tt class="code">Neuron1</tt>, likewise
for <tt class="code">Neuron2</tt>): </p>
<pre class="programlisting">void Neuron1::apply_vis(VisitorBase &amp; vis)<br>{<br>  InstData::apply_impl(vis);<br>}    </pre>
<p> Finally, the 'visitable part' of the policy <tt class="code">Data1</tt>
(the data that the visitor wants to access, <tt class="code">a_</tt>
here) has to be moved in the specialised instantiation <tt class="code">Data1&lt;void&gt;</tt>
from which derive all the <tt class="code">Data1&lt;TypeImpl&gt;</tt>.
The function <tt class="code">apply_impl</tt> has also to be defined
in its body (here with a solution using <tt class="code">dynamic_cast</tt>
to check the compatibility of the visitor), as shown in Listing 11.<br>
</p>
<table class="sidebartable">

    <tr>
      <td style="vertical-align: top;">
      <pre class="programlisting">template &lt;class TypeImpl&gt; class Data1;    </pre>
      <pre class="programlisting">template &lt;&gt;<br>class Data1&lt;void&gt;<br>{<br>  friend class DataVisitor;<br>protected:<br>  Data1(double a) : a_(a) {}<br>  const double &amp; a_impl() const {return a_;}<br>  void apply_vis_impl(VisitorBase &amp; vis)<br>  {<br>    Visitor&lt;Data1&lt;void&gt; &gt; * pv = <br>        dynamic_cast&lt;Visitor&lt;Data1&lt;void&gt; &gt; *&gt;(&amp; vis);<br>    if (pv) pv-&gt;visit(*this);<br>  }<br>private:<br>  const double a_;<br>};    </pre>
      <pre class="programlisting">template &lt;class TypeImpl&gt;<br>class Data1<br>  : public Data1&lt;void&gt;<br>{<br>protected:<br>  typedef double TypeInit;<br>  Data1(TypeInit a = 0.) : Data1&lt;void&gt;(a) {}<br>};<br></pre>
      </td>
    </tr>
    <tr>
      <td class="title">Listing 11
      </td>
    </tr>

</table>
<p> This way, the argument of the call of <tt class="code">visit</tt>
is the parent object of type <tt class="code">Data1&lt;void&gt;</tt>
instead of the object itself. The cost of the passage of the visitor is
thus a <tt class="code">dynamic_cast</tt> plus a virtual function
call. In the case the visitor is not compatible, nothing is done here,
but an error could be thrown or returned by the method <tt class="code">apply_impl</tt>.
Likewise with <tt class="code">Data2&lt;void, void&gt;</tt> for the
visitable part of <tt class="code">Data2</tt>. </p>
<h2> Policy Bridge design for an arbitrary number of policies </h2>
<p> In the end, the code can be abstracted to bridge N policies (the
dedicated methods such as <tt class="code">update</tt>, etc. are
'decentralised' in derived classes), in Listing 12 with N = 15.<br>
</p>
<table class="sidebartable">

    <tr>
      <td style="vertical-align: top;">
      <pre class="programlisting">template &lt;class GetPolicy0<br>  , ...<br>  , class GetPolicy14&gt;<br>class PolicyBridge15<br>  : public GetPolicy0::template<br>       apply&lt;PolicyBridge15&lt;GetPolicy0, ...,<br>          GetPolicy14&gt; &gt;::Type<br>    , ...<br>    , public GetPolicy14::template<br>         apply&lt;PolicyBridge15&lt;GetPolicy0, ...,<br>            GetPolicy14&gt; &gt;::Type<br>{<br>protected:<br>  typedef GetPolicy0::template <br>apply&lt;PolicyBridge15&gt;::Type<br>    InstPolicy0;<br>  ...<br>  typedef GetPolicy14::<br>    template apply&lt;PolicyBridge15&gt;::<br>    Type InstPolicy14;    </pre>
      <pre class="programlisting">  friend InstPolicy0;<br>  ...<br>  friend InstPolicy14;    </pre>
      <pre class="programlisting">  typedef typename InstPolicy0::TypeInit TypeInit0;<br>  ...<br>  typedef typename InstPolicy14::<br>     TypeInit TypeInit14;    </pre>
      <pre class="programlisting">  PolicyBridge15(TypeInit0 var_init0<br>      , ...<br>      , TypeInit14 var_init14)<br>    : InstPolicy0(var_init0)<br>    , ...<br>    , InstPolicy14(var_init14)<br>  {}<br>};<br></pre>
      </td>
    </tr>
    <tr>
      <td class="title">Listing 12
      </td>
    </tr>

</table>
<p> This design requires each policy to define a type <tt class="code">TypeInit</tt>,
which is set to a 'fake void' type <tt class="code">NullType</tt> when
no initialisation variable is required (same <tt class="code">NullType</tt>
as used for <tt class="code">TypeList</tt> in [<a
 href="#Alexandrescu01">Alexandrescu01</a>]). The
overriding of the pure virtual functions defined in the interface are
left to the implementation of the instantiated types here. A class <tt
 class="code">Neuron1</tt> is derived from a suitable instantiation as
shown in Listing 13.<br>
</p>
<table class="sidebartable">

    <tr>
      <td style="vertical-align: top;">
      <pre class="programlisting">class Neuron1<br>  : public PolicyBridge2&lt;GetData1, GetUpdateMech1&gt;<br>  , public InterfaceBase<br>{<br>public:<br>  Neuron1(TypeInit0 a)<br>    : PolicyBridge2&lt;GetData1, GetUpdateMech1&gt;(<br>       a, NullType()) {}<br>  void update()<br>  {<br>    GetUpdateMech1::apply&lt;PolicyBridge2&lt;GetData1,<br>        GetUpdateMech1&gt;<br>      &gt;::Type::update_impl();<br>  }<br>  const double &amp; a() { ... }<br>  void &amp; apply_vis(VisitorBase &amp; vis) { ... }<br>};  </pre>
      </td>
    </tr>
    <tr>
      <td class="title">Listing 13
      </td>
    </tr>

</table>
<p> A dedicated version of <tt class="code">PolicyBridge2</tt> could
be written to create neurons with the common interface hard-wired: <tt
 class="code">InterfaceBase</tt> should be put in the template argument
list and the methods <tt class="code">update</tt>, <tt class="code">a</tt>
and <tt class="code">apply</tt> can be centralised in the <tt
 class="code">PolicyBridge2bis</tt> code (to save some code lines),
shown in Listing 14.<br>
</p>
<table class="sidebartable">

    <tr>
      <td style="vertical-align: top;">
      <pre class="programlisting">template &lt;...&gt;<br>PolicyBridge2bis&lt;InterfaceBase, GetData, GetUpdateMech&gt;<br>{<br>  void update() <br>  {<br>    GetUpdateMech::template &lt;...&gt;::<br>    Type::update_impl();<br>  }<br>  ...<br>};<br></pre>
      </td>
    </tr>
    <tr>
      <td class="title">Listing 14
      </td>
    </tr>

</table>
<p> The code of <tt class="code">PolicyBridgeN</tt> can be generated
for all values of N in a define range using preprocessor macros such as
<tt class="code">REPEAT</tt> (cf. <tt class="code">boost::preprocessor</tt>
[<a href="#Boost">Boost</a>], the TTL library [<a href="#Tiny">Tiny</a>]),
i.e. to create the class templates <tt class="code">PolicyBridge1</tt>
up to <tt class="code">PolicyBridgeN</tt>,
where <tt class="code">N</tt> is an arbitrary limit. </p>
<p> See <a href="http://www.bionicear.org/people/gilsonm/prog.html">http://www.bionicear.org/people/gilsonm/prog.html</a>
for details
on this implementation. </p>
<h2> Conclusion </h2>
<p> The policy bridge pattern aims to build classes that inherit
'properties' or functionalities from a certain number of policies
(variable and function members from the protected 'space'). Each policy
can call members from other ones and the compatibility between the
policies is checked at compile time. This approach is modular and
flexible, and keeps the design of policies related to distinct
functionalities somehow 'orthogonal'. </p>
<p> A common interface can be designed in order to provide a main
'gate' (to all the common functionalities that have to be public, and
the cost is the one of a virtual-function call), to store them in
standard containers, etc. Moreover, specific interfaces can similarly
be design for particular functionalities belonging to a restrained
number of mechanisms, allowing us to pilot the bridged objects
according to what they are actually made of. Usual visitors can be
adapted and applied to these objects in order to interact with some of
the policies involved in the design. Meta-functions can help and bring
further refinement to use policies with more than one template
parameter. </p>
<p> Such design proved to be useful and efficient in a simulation
program where objects of various types interact: for instance neurons
with distinct intern mechanisms, as well as diverse synapses to connect
them; these objects are created at the beginning of the program
execution and they evolve and interact altogether during the
simulation. Requirements such as 'fast' object creation or deletion
have not been considered here so far, 'optimisation' was sought for
only for the function calls (call via the common interface class).
Visitors were used for adequate object construction and linking objects
from distinct kind (in particular between synapses and neurons to check
compatibility when creating a synaptic connection), but not used during
the execution: the interface then provides a faster way to access the
functionalities of the objects. </p>
<p> Code is available online at
<a href="http://www.bionicear.org/people/gilsonm/index.html">http://www.bionicear.org/people/gilsonm/index.html</a>
to illustrate how
such a design can be used.<br>
</p>
<h2> Acknowledgements </h2>
<p> The author thanks Nicolas di Cesare for earlier discussion about
design pattern, and Alan Griffiths, Phil Bass and Roger Orr for very
helpful comments that brought significant improvements of the text
during the review process. MG is funded by a scholarship from the NICTA
Victorian Research Lab (<a href="http://www.nicta.com.au">www.nicta.com.au</a>).
</p>
<h2> References </h2>
<p class="reference"> [<a name="Alexandrescu01">Alexandrescu01</a>]
A. Alexandrescu. <i>Modern
C++ design: generic programming and design patterns applied</i>,
Addison-Wesley, Boston, MA: 001. Includes bibliographical references
and index. </p>
<p class="reference"> [<a name="VandevoordeJosuttis03">Vandevoorde/Josuttis03</a>]
David Vandevoorde,
Nicolai M. Josuttis <i>C++ templates : the complete guide</i>, Addison
Wesley, 2003. </p>
<p class="reference"> [<a name="Boost">Boost</a>] Boost c++
libraries.
<a href="http://www.boost.org/">http://www.boost.org/</a> </p>
<p class="reference"> [<a name="Tiny">Tiny</a>] Tiny Template
Library.
<a href="http://tinytl.sourceforge.net/">http://tinytl.sourceforge.net/</a>
</p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
