    <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  :: Tiny Template Tidbit</title>
        <link>https://members.accu.org/index.php/journals/416</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 #47 - Feb 2002 + 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/c198/">47</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/c198-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c198+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;Tiny Template Tidbit</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 February 2002 16:46:09 +00:00 or Tue, 26 February 2002 16:46:09 +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="d0e18" id="d0e18"></a></h2>
</div>
<p>I am constantly amazed at what can be done with templates. I
started programming in C around 1985 and in C++ only around 1995.
Most of my work over the past 6 years has involved using C++ to the
maximum of my abilities, but only for three years have I been
working with templates. In this article I would like to share a
very small template tidbit, something I think is really cool. I
hope it can stimulate your interest in using template capabilities
for your own code, or just be another &quot;trick&quot; to put in your bag,
something I think fairly easy to remember.</p>
<p>I will assume in this article that you are at least familiar
with a few of the STL class templates, and, though you may not have
written your own class templates before, you have &quot;seen how it's
done&quot;.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e24" id="d0e24"></a>Problem
statement</h2>
</div>
<p>We have an application in which a set of objects is being
generated by a third-party library and stored in a container. For
simplicity, I will refer to the objects as &quot;points&quot;. Objects of
this class don't necessarily have much intrinsic behavior, and are
used by other classes of objects or functions for complex
computations. For instance, an object (which I call a processor for
clarity) might use the set of points to create a spline curve that
best fits the points. That is, each point is simply a 2D
coordinate, an aggregate of two numbers:</p>
<pre class="programlisting">
struct Point {float x,y;};
std::set&lt;Point&gt; points;
</pre>
<p>Yet, as the application evolves, it is likely that objects of
the <tt class="classname">Point</tt> class will become more
complex. Perhaps other state data, such as local temperature,
contact normal, density, etc, will be &quot;carried around&quot; along with
the coordinates of the point. In this case, the <tt class=
"classname">Point</tt> class suddenly changes from <span class=
"emphasis"><em>being the data</em></span> to being an aggregate of
a data object and the other state data:</p>
<pre class="programlisting">
struct Coord {float x,y;};
        // coordinates in 2D space
struct Vec {float x,y;};
        // vector in 2D space
struct Point {
  Coord coords;
        // the coordinate pair of the point
  Vec contactNormal;
        // new state data associated with point
  float temperature, density;
       // other state data...
};
std::set&lt;Point&gt; points;
</pre>
<p>The &quot;curve fitter&quot; processor mentioned earlier suddenly no
longer works since it was designed to use the point as a 2D
coordinate pair, not as an object <span class=
"emphasis"><em>containing</em></span> the 2D coordinate pair as a
data member.</p>
<p>Assuming the curve-fitter could be designed to compile in both
cases, the application may evolve such that the 2D coordinates of
the point are no longer a publicly accessible attribute, but rather
a private data member than can only be accessed via a const &quot;get&quot;
method (or even computed on-the-fly instead of being a data
member). This could happen when <tt class="classname">Point</tt>
starts having behavior of its own, not necessarily relevant to the
curve-fitting operation of the processor. Since the latter was
designed to access an attribute, it no longer accepts the new class
of <tt class="classname">Point</tt>. For instance,</p>
<pre class="programlisting">
struct Foo1 {int bar;};
struct Foo2 {int bar() const;};
</pre>
<p>Both should be adequate for the curve-fitter, yet the latter
would fail to compile if <span class="structname">Foo2</span> is
used instead of <span class="structname">Foo1</span>, complaining
that <tt class="function">bar()</tt> is not an attribute (or some
equivalent hard-to-decode error message, different for every
compiler). Does the processor really care how the data is
acquired?</p>
<p>If this weren't enough, the container type may change, yet the
processor object (curve-fitter in this example) does not care: a
<tt class="classname">std::vector</tt>, a <tt class=
"classname">std::list</tt>, a <tt class="classname">std::set</tt>,
or a <tt class="classname">your::container</tt>, as long as the
data is there, the processor should be satisfied. This is trivial
to adapt to, as you will see below, but more importantly, what if
the container stores pointers to the points rather than the actual
points? This is likely to happen if copying <tt class=
"classname">Point</tt> is onerous and you need to avoid copying
those objects in your application, so you change the container type
from containing <tt class="constant">Point</tt> to containing
<tt class="type">Point*</tt>. Suddenly, the curve-fitter no longer
compiles since it expects each element of the container to be an
object, not a pointer to an object.</p>
<p>Finally, our processor (object or function) may be used in
different modules, or even different applications we build, perhaps
for related yet distinct application domains. Do we want to have 10
different versions of the same code, one for each possible
container type and point design?</p>
<p>It turns out that templates can be used in C++ to make one
processor (object or function) that accepts any container that uses
iterators AND, much more interestingly, is able to extract the
needed data from the container elements, regardless of whether the
container element type</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Is the data, or is a pointer to the data (as opposed to
containing it)</p>
</li>
<li>
<p>Is an object or pointer to object <span class=
"emphasis"><em>containing</em></span> the data</p>
</li>
<li>
<p>Makes data available as attribute or method</p>
</li>
</ul>
</div>
<p>Moreover, templates allow you to do so <span class=
"emphasis"><em>at compile time</em></span>, and <span class=
"emphasis"><em>automatically</em></span>, without your
intervention. Yep, no kidding! Hopefully, you can see that the
above is a fairly generic problem, unrelated to the particular
application domain (curve-fitting) in which I encountered it.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e118" id="d0e118"></a>Solution</h2>
</div>
<p>Let's start simple and try to keep things simple. Assume we have
a function called <tt class="function">fitCurve</tt> that takes a
container of points and finds the curve that best fits the set,
returning the result as a <tt class="classname">Curve</tt> object.
We are not concerned with the definition of the <tt class=
"classname">Curve</tt> class. To be generic, let's call the point
class <tt class="classname">Coord</tt> and the container of points
<tt class="classname">Coords</tt>:</p>
<pre class="programlisting">
#include &quot;Curve.hh&quot;
#include &quot;Coord.hh&quot;
typedef std::list&lt;Coord&gt; Coords;
Curve fitCurve(const Coord&amp; coords);
</pre>
<p>This function can be used only to fit a curve to a set of
<tt class="classname">Coord</tt> objects stored in a <tt class=
"classname">std::list</tt>. If you have a set of <tt class=
"classname">Coord</tt>s in a <tt class="classname">std::set</tt> or
a <tt class="classname">std::vector</tt>, <tt class=
"function">fitCurve</tt> cannot be used. Why should the interface
force us to use one type, when <tt class="function">fitCurve</tt>
only cares that the set is ordered? If you want to use STL
containers, then the containers are not related by inheritance, but
they do share common interfaces for certain operations. For
instance, they all have an iterator type nested. Let's make
<tt class="function">fitCurve</tt> independent of the container
type. We use templates to parameterize <tt class=
"function">fitCurve</tt> on the container type, for instance</p>
<pre class="programlisting">
// note: syntax wrong but you get the idea:
template &lt;class Container&gt;
Curve fitCurve(const Container&lt;Coord&gt;&amp; coords)
{
  // ...
  // set coord1 to first Coord in coords
  // set coord2 to second Coord in coords
  Coord c = coord1 + coord2;
  // ...
}
</pre>
<p>The only requirement on the element type (<tt class=
"classname">Coord</tt>) in the container is that it have an
<tt class="methodname">operator+</tt> defined. The requirement on
the container is that we use <tt class=
"classname">Container::iterator</tt> instead of other access
operators such as <tt class="methodname">operator[]</tt> to access
the individual elements of the container.</p>
<p>What are some of the advantages and disadvantages of
parameterizing? I can think of the following:</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e187" id=
"d0e187"></a>Advantages:</h2>
</div>
<p>Any kind of container, whose concrete type is known at compile
time, can be given to the curve fitter. For each new type of
container, the compiler takes the &quot;function template&quot; (i.e. a
template for a function) and generates a &quot;template function&quot; (i.e.
a function that comes from a template) - the order of those words
matters. There will be a few constraints on the operations required
from the container, but this is already far better than being stuck
with one container class. The alternative would be to copy all the
elements from your container to the container expected by
<tt class="function">fitCurve</tt>.</p>
<p>Since <tt class="function">fitCurve</tt> is a function, most
compilers will know to generate the template function for the given
container without your having to specify it explicitly. The mere
act of calling <tt class="function">fitCurve</tt> with your
container is enough, since the compiler knows the type of container
you are using, and can generate the template function
automatically.</p>
<p>For the same reason, you can change the type of your container
at some later stage of development, without having to do anything
to <tt class="function">fitCurve</tt>: the compiler and your build
environment will know that the old &quot;template function&quot; should be
changed to a new one, at compilation time, and will do the change
for you.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e208" id=
"d0e208"></a>Disadvantages:</h2>
</div>
<p>Every template function that is generated by the compiler means
extra code. This is the famous &quot;code bloat&quot; problem of class and
function templates. This is a factor to consider only if you plan
on using several different containers in the same application
(which is not necessarily the case), and memory footprint
matters.</p>
<p>It can be difficult to predict how &quot;well behaved&quot; is the
<tt class="classname">Container</tt> (template) class. Can it throw
exceptions? Does its interface properly identify what is const and
non-const? Can this invalidate the algorithm that accesses the
<tt class="classname">Container</tt>? There will always be cases
where the disadvantages outweigh the advantages, but I have found
the reverse to be true much more often.</p>
<p>The next step is to allow the container element type to be a
pointer to a <tt class="classname">Coord</tt> as well as a
<tt class="classname">Coord</tt>. Intuitively, we know it should be
possible: the compiler knows exactly what is the type of what is
contained: i.e., a <tt class="classname">Coord</tt> or a pointer to
a <tt class="classname">Coord</tt>. When the element type is a
pointer to <tt class="classname">Coord</tt>, the above piece of
code would have <tt class="varname">coord1</tt> and <tt class=
"varname">coord2</tt> be pointers to <tt class=
"classname">Coord</tt> objects rather than actual <tt class=
"classname">Coord</tt> objects. Wouldn't it be nice if we could
write, in the above code, something like:</p>
<pre class="programlisting">
const Coord&amp; c1 = getCoord(coord1);
const Coord&amp; c2 = getCoord(coord2);
Coord sum = c1 + c2;
</pre>
<p>If the element type is a <tt class="classname">Coord</tt>, then
<tt class="function">getCoord(coord1)</tt> just returns <tt class=
"varname">coord1</tt>. If on the other hand it is a <tt class=
"type">Coord*</tt>, then <tt class="function">getCoord(coord1)</tt>
returns <tt class="type">*coord1</tt>. Simple overloading allows us
to do that:</p>
<pre class="programlisting">
const Coord&amp; getCoord(const Coord&amp; v)
  {return v;}
const Coord&amp; getCoord(const Coord* v)
  {return *v;}
</pre>
<p>Now things are going to get a little more interesting. We want
to allow the element type of the container be something else than a
<tt class="classname">Coord</tt>, i.e. it could be a <tt class=
"classname">Point</tt> that <span class=
"emphasis"><em>contains</em></span> a <tt class=
"classname">Coord</tt>. All we need is to overload <tt class=
"methodname">getCoord()</tt> once more for the case where
<tt class="varname">v</tt> is a <tt class=
"classname">Point</tt>:</p>
<pre class="programlisting">
const Coord&amp; getCoord(const Point&amp; v)
  {return v.coords;}
</pre>
<p>Of course, we want to be able to use our own class instead of
<tt class="classname">Point</tt>. Templates come to the rescue once
again:</p>
<pre class="programlisting">
template &lt;class POINT&gt;
const Coord&amp; getCoord(const POINT&amp; v)
  {return v.coords;}
</pre>
<p>This requires that <tt class="classname">POINT</tt>, the type of
object contained by Container in <tt class=
"function">fitCurve</tt>, have a publicly visible &quot;<tt class=
"classname">coords</tt>&quot; data member. So it's not totally generic
but again, far better than being stuck with only <tt class=
"classname">Point</tt> and <tt class="classname">Coord</tt>
objects!</p>
<p>Before dealing with the member &quot;attributes vs. methods&quot; problem,
the last requirement is that the container can contain pointers to
point types that contain the <tt class="classname">Coord</tt> data
as a data member. What we need is a template overload for
pointers:</p>
<pre class="programlisting">
template &lt;class POINT&gt;
const Coord&amp; getCoord(const POINT* p)
  {return p-&gt;coords;}
</pre>
<p>It is somewhat like &quot;partial specialization&quot; because some of the
type information is still general and unknown (<tt class=
"classname">POINT</tt> could be anything) but some is specific: it
must be a pointer to something. However &quot;partial specialization&quot;
specifically refers to specialization of a subset of the template
parameters in a multi-parameter template definition.</p>
<p>Let's summarize what we have so far:</p>
<pre class="programlisting">
/// General function template
template &lt;typename POINT&gt; inline
const Coord&amp; getCoord(const POINT&amp; p)
  {return p.coords;}

/// Partial specialization for pointers
/// to things
template &lt;class POINT&gt;
const Coord&amp; getCoord(const POINT* p)
  {return p-&gt;coords;}

/// Complete specialization for Coord
inline
const Coord&amp; getCoord(const Coord&amp; p)
  {return p;}

/// Complete specialization for pointer
/// to Coord
inline
const Coord&amp; getCoord(const Coord* p)
  {return *p;}
</pre>
<p>With those four <tt class="function">getCoords</tt> put
together, we have the following scenario:</p>
<p>If the element type of the container is anything but a
<tt class="classname">Coord</tt> or <tt class="type">Coord*</tt>,
it will use the first or second definition of <tt class=
"function">getCoord</tt>, depending on whether or not <tt class=
"function">getCoord</tt> is called with a pointer to a <tt class=
"classname">POINT</tt> or a <tt class="classname">POINT</tt>
itself;</p>
<p>Otherwise, it will use the appropriate complete specialization
of <tt class="function">getCoord</tt>, depending on whether or not
<tt class="function">getCoord</tt> is called with a pointer to a
<tt class="classname">Coord</tt> or a <tt class=
"classname">Coord</tt> itself.</p>
<p>Our <tt class="function">fitCurve()</tt> is now able to handle
four cases of data sets:</p>
<pre class="programlisting">
Container&lt;Coord&gt;
Container&lt;Coord*&gt;
Container&lt;Something&gt;
Container&lt;Something*&gt;
</pre>
<p>The compiler can choose the right version of <tt class=
"function">getCoord</tt> to use at compilation time. In the last
two cases, as long as <tt class="classname">Something</tt> has a
public data member called &quot;<tt class="varname">coords</tt>&quot;, we are
ok. <tt class="classname">Container</tt> can be any class that
provides an iterator type (or whatever operations are required by
the processor object or function).</p>
<p>The last generalization that we must do is to allow the
&quot;<tt class="varname">coords</tt>&quot; to be a method instead of a data
member. For instance,</p>
<pre class="programlisting">
class Point {
public:
  const Coord&amp; coords() const
    {return coords_;}
private:
  Point coords_;
};
</pre>
<p>You probably know how to &quot;point&quot; to a method in a class. For
instance, the &quot;<tt class="methodname">coords</tt>&quot; method can be
pointed to with a pointer of type &quot;<tt class="type">const
Coord&amp; (Point::*)() const</tt>&quot;. Given a typedef</p>
<pre class="programlisting">
typedef const Coord&amp;
                (Point::* Method)() const;
</pre>
<p>This <tt class="literal">typedef</tt> defines a new type called
<tt class="type">Method</tt>, as a pointer to a const method of the
<tt class="classname">Point</tt> class returning a reference to a
const <tt class="classname">Coord</tt>. If this seems horribly
difficult to read, don't worry, you're not the only one who feels
that way. Pointers to functions and methods is one of the
idiosyncrasies of C++. The syntax is atrociously difficult to get
your mind around, but I guess it could be worse. In any case once
you've done a few examples on your own it gets better. Here is an
example of using a <tt class="type">Method</tt> object:</p>
<pre class="programlisting">
Method mm = &amp; Point::coords;
      // store pointer to coords method
Point point; // create a Point object
Coord coords = (point.*mm)();
      // #1: call coords method on it
Coord coords = point.coords();
      // #2: exact same thing
</pre>
<p>The line #2 does <span class="emphasis"><em>exactly</em></span>
the same thing as #1.</p>
<p>So the question is whether there is a way of doing the same
thing with <span class="emphasis"><em>data members</em></span>.
Indeed, when <tt class="function">getCoord</tt> accesses the
<tt class="varname">coords</tt> field of the class, the compiler
knows exactly what &quot;<tt class="varname">coords</tt>&quot; is: a data
member or a method. So if we could write the general <tt class=
"function">getCoord</tt> template like</p>
<pre class="programlisting">
template &lt;class POINT&gt;
const Coord&amp; getCoord(const POINT&amp; v) {
  return getData(v, &amp;POINT::coords);
}

// partial specialization for pointers
template &lt;class POINT&gt;
const Coord&amp; getCoord(const POINT* v) {
  return getData(*v, &amp;POINT::coords);
}
</pre>
<p>and properly define two <tt class="function">getData</tt>
functions, one accepting a pointer to a method as second argument,
and another accepting a pointer to a <span class=
"emphasis"><em>data member</em></span> as second argument, we have
accomplished our goal. The compiler will know which to choose
without us having to tell it. In pseudo-language:</p>
<pre class="programlisting">
inline const Coord&amp;
getData(const Point&amp; pp, Method mm) {
  return (pp.*mm)();
}

inline const Coord&amp;
getData(const Point&amp; pp, ptr_dmem_Point dd) {
  return ...;
}
</pre>
<p>where <tt class="type">Method</tt> is the typedef described
earlier, <tt class="varname">ptr_dmem_Point</tt> stands for
&quot;pointer to data member of <tt class="classname">Point</tt>&quot; and
the ellipsis just means &quot;don't know the syntax yet&quot;. It took me a
bit of trial and error to find out the correct syntax, but it turns
out it's not too bad: a &quot;pointer&quot; to a data member of type
<tt class="type">T</tt> for a class <tt class=
"classname">Point</tt> is &quot;<tt class="type">T Point::*</tt>&quot;.
Simpler than defining a pointer to a method.</p>
<p>Our final solution for the <tt class="function">getData</tt> is
therefore, after replacing <tt class="classname">Point</tt> by a
template parameter<sup>[<a name="d0e497" href="#ftn.d0e497" id=
"d0e497">1</a>]</sup>:</p>
<pre class="programlisting">
template &lt;typename POINT&gt;
inline const Coord&amp;
getData(const POINT&amp; pp, Coord POINT::* dd) {
  return pp.*dd;
}

template &lt;typename POINT&gt;
inline const Coord&amp;
getData(const POINT&amp; pp,
        const Coord&amp; (POINT::* mm)() const) {
  return (pp.*mm)();
}
</pre>
<p>with the four function templates for <tt class=
"function">getCoord</tt> mentioned above.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e510" id=
"d0e510"></a>Discussion</h2>
</div>
<p>What does this give us?</p>
<p>Our <tt class="function">fitCurve</tt> can use any container of
<tt class="classname">Coord</tt>, <tt class="type">Coord*</tt>,
<tt class="classname">Something</tt>, or <tt class=
"type">Something*</tt>, as long as the container has an &quot;<tt class=
"type">iterator</tt>&quot; type defined in it, or whatever methods are
required by <tt class="function">fitCurve</tt> (<tt class=
"literal">!=</tt>, <tt class="literal">++</tt>, etc).</p>
<p>&quot;<tt class="classname">Something</tt>&quot; must have a &quot;<tt class=
"type">coords</tt>&quot; field, which must be either a <tt class=
"classname">Coord</tt> or a &quot;const method returning a reference to
a const <tt class="classname">Coord</tt>.&quot;</p>
<p>If we make any changes to our container type, no changes are
needed to <tt class="function">fitCurve</tt>, as long as the
changes satisfy the minimal requirements of 1.</p>
<p>If we make any changes to the type of object stored in the
container, no changes are needed to <tt class=
"function">fitCurve</tt>, as long as the new object is something
that satisfies 2. above;</p>
<p>The compiler, as it recompiles the class that uses <tt class=
"function">fitCurve</tt>, will make use of the correct <tt class=
"function">getCoord</tt> and <tt class="function">getData</tt>
without our intervention. This is probably the biggest gain.</p>
<p>Since everything is inlined, there are no function calls
involved: everything is resolved at compile time and is equivalent
to your having typed the <tt class="type">coords</tt> data member
straight where it is used by the processor object or function.</p>
<p>We now have a far more generic processor with only 15 lines of
extra code, and one that requires almost NO intervention on our
part when using the fitter with a new or different type of
container and contained objects. Pretty good for 15 lines of
code.</p>
<p>For a library developer, this level of generality may still be
insufficient: the member in <tt class="classname">POINT</tt> must
be called &quot;<tt class="type">coords</tt>&quot;. This is similar to STL
containers which all have a member called &quot;<tt class=
"type">iterator</tt>&quot; that defines an iterator appropriate for the
container. To make it completely general, we would need a way of
allowing the user to specify that they want something other than
&quot;coords&quot; to be used by <tt class="function">getCoord()</tt>. One
work-around would be to define further complete specializations for
your point class, using the appropriate member:</p>
<pre class="programlisting">
template &lt;&gt;
inline const Coord&amp;
getCoord(const YourPoint&amp; v) {
  return getData(v, &amp;YourPoint::yourCoords);
}
</pre>
<p>and similarly for the pointer version. This is tedious to type
and error-prone, but only a macro could be used to simplify this to
a one-liner:</p>
<pre class="programlisting">
#define GET_COORD(YourPoint, yourData) \
template &lt;&gt; \
  inline const Coord&amp; \
  getCoord(const YourPoint&amp; v) { \
    return getData(v, &amp;YourPoint::yourData);\
  } \
template &lt;&gt; \
  inline const Coord&amp; \
  getCoord(const YourPoint* v) { \
    return getData(*v, &amp;YourPoint::yourData);\
  }
</pre>
<p>which would allow you to type</p>
<pre class="programlisting">
GET_COORD(YourPointClass, yourCoordMember)
</pre>
<p>in your source file to get the specialization. The good news is
that if you forget to define this, you get a compile time error.
The bad news is that you have to define it in a place where it is
visible to the compiler by the time your processor object or
function calls <tt class="function">getCoord</tt>, which is likely
to increase the coupling between header files. The only other way
that I can think of is to derive your class and provide a
&quot;<tt class="type">coords</tt>&quot; alias for the member, but this will
be useful only if you have any control over the type of object
stored in the container. For instance, you could derive <tt class=
"classname">YourPointClass</tt> as</p>
<pre class="programlisting">
struct PointDerived: YourPointClass {
  Coord&amp; coords;
    // alias for member in YourPointClass
  PointDerived: coords(yourCoordMember) {}
};
</pre>
<p>and use a container of <tt class="classname">PointDerived</tt>
objects instead of a container of <tt class=
"classname">YourPointClass</tt> objects. This only works if you
have control over the element type of the container.</p>
<p>It is interesting to notice that templates are necessary in C++
only because C++ is such a strongly typed language. Consider
Python, which is essentially untyped: classes are not
differentiated by type, only by name. Hence a List class in Python
that takes as argument the name of an object to store in the list,
can have that object be any class of object. The idea of templates
in Python is implicit in some ways, and unnecessary in others.
There are probably many other languages where this applies. The
strong-typing nature of C++ requires extra typing (sorry for pun),
but it allows the compiler to know much more about the data being
handled, and therefore to do much more stringent error-checking and
optimizations not possible in weakly typed languages. Templates in
C++ are necessary so C++ can support very useful features found in
other high-level languages in a strongly-typed and optimized
context.</p>
<p>Note: At the time of this writing, GNU g++ 3.0 (on SGI) has
problems picking the correct getCoord: it seems to get confused by
the pointer overloads. The code compiles and works perfectly,
however, with SGI's MipsPro C++ compiler 7.3.1.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e635" id="d0e635"></a>Summary</h2>
</div>
<p>I showed how a processor (object or function) that uses data
from a set of objects can be generalized with a very small number
of lines of code, using templates and template specialization, to
support application evolution, without requiring you to adapt the
processor. More specifically, your processor object or function is
able to extract the needed data from the container elements,
regardless of whether the container element type.</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p><span class="emphasis"><em>Is</em></span> the data, or is a
pointer to the data (as opposed to containing it)</p>
</li>
<li>
<p>Is an object or pointer to object <span class=
"emphasis"><em>containing</em></span> the data</p>
</li>
<li>
<p>Makes data available as <span class=
"emphasis"><em>attribute</em></span> OR <span class=
"emphasis"><em>method</em></span></p>
</li>
</ul>
</div>
<p>Moreover, the compiler does so for you, automatically, without
requiring your intervention. I'll gladly reply via email to
suggestions and ideas. Sincere thanks to Phil Bass for his critical
comments and ideas.</p>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e662" id="d0e662"></a>References</h2>
</div>
<div class="bibliomixed">
<p class="bibliomixed">Bjarne Stroustrup, <span class=
"citetitle"><i class="citetitle">C++ Programming Language, third
edition</i></span></p>
</div>
<div class="bibliomixed">
<p class="bibliomixed">Andrei Alexandrescu, <span class=
"citetitle"><i class="citetitle">Modern C++ Design</i></span></p>
</div>
<div class="bibliomixed">
<p class="bibliomixed">Mark Lutz, <span class="citetitle"><i class=
"citetitle">Python Programming, second edition</i></span></p>
</div>
</div>
</div>
<div class="footnotes"><br>
<hr class="c2" width="100">
<div class="footnote">
<p><sup>[<a name="ftn.d0e497" href="#d0e497" id=
"ftn.d0e497">1</a>]</sup> It is not currently possible, most
unfortunately, to define templated typedefs. Hence writing the
following is not possible, even though it would make perfect
sense:</p>
<pre class="programlisting">
template &lt;typename POINT&gt; typedef
  const Coord&amp; (POINT::* Method)() const;
</pre></div>
</div></p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
