    <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 Curious Case of the Compile-Time Function</title>
        <link>https://members.accu.org/index.php/articles/239</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>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + Overload Journal #62 - Aug 2004</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/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c150/">62</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-150/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+150/">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 Curious Case of the Compile-Time Function</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 01 August 2004 22:52:11 +01:00 or Sun, 01 August 2004 22:52:11 +01:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h3>(An Exercise in Template
Meta-Programming)</h3>
<h2><a name="d0e20" id="d0e20"></a>A Crime Has
Been Committed</h2>
</div>
<p>18 months ago I described a version of my Event/Callback library
in an Overload article [<a href="#Bass">Bass</a>]. This library is
used extensively in my employer's control systems software. A
typical use looks like this:</p>
<div class="sidebar">
<p class="title c3">Exhibit 1: The event/callback library in
action.</p>
<pre class="programlisting">
// A class of objects that monitor some event.
class Observer {
public:
  Observer(Event&lt;int&gt;&amp; event)
    : callback(bind_1st(memfun(
                  &amp;Observer::handler), this))
    , connection(event, &amp;callback) {}
private:
  void handler(int);  // the event handler
  typedef Callback::Adapter&lt;
               void (Observer::*)(int)&gt;::type
      Callback_Type;
  Callback_Type callback; // a function object
  Callback::Connection&lt;int&gt; connection;
                         // event &lt;-&gt; callback
};
</pre></div>
<p>The key feature in this example is that a callback and an
event/callback connection are both stored in the <tt class=
"classname">Observer</tt> as data members. Some attempt has been
made to support this idiom by providing various helpers (the
<tt class="function">bind_1st()</tt> and <tt class=
"function">memfun()</tt> function templates<sup>[<a name="d0e44"
href="#ftn.d0e44" id="d0e44">1</a>]</sup> and the <tt class=
"classname">Callback::Adapter&lt;Pmf&gt;</tt> class template).
However, there is still quite a lot of rather verbose boilerplate
code. And that's a crime.</p>
<p>It has been clear for some time that we should be able to
improve on this. There seems to be no fundamental reason, for
example, why we can't combine the callback and its connection into
a single class template (<tt class="classname">Bound_Callback</tt>,
say) and use it like this:</p>
<div class="sidebar">
<p class="title c3">Exhibit 2: The goal.</p>
<pre class="programlisting">
// A class of objects that monitor some event.
class Observer {
public:
  Observer(Event&lt;int&gt;&amp; event)
     : callback(event, &amp;Observer::handler,
                this) {}
private:
  void handler(int);  // the event handler
  Bound_Callback&lt;void (Observer::*)(int)&gt;
     callback;
};
</pre></div>
<p>The question is how should we write the <tt class=
"classname">Bound_Callback&lt;Pmf&gt;</tt> template?</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e72" id="d0e72"></a>Suspects and
Red Herrings</h2>
</div>
<p>The first thing that comes to mind is Boost [<a href=
"#boost">boost</a>]. There's bound to be a Boost library that
provides what we need. The trouble is I can't find one.</p>
<p>Boost.Bind provides a lovely family of <tt class=
"function">bind()</tt> functions that generate all kinds of
function objects. Unfortunately, their return types are
unspecified, so we can't declare data members of those types.</p>
<p>Then there's Boost.Function, which was designed for a very
similar job and does provide types we can use as data members. I
believe we could, in fact, use the <tt class=
"function">boost::function&lt;&gt;</tt> template as the callback
part of our <tt class="classname">Bound_Callback</tt>. What I
haven't told you, though, is that an <tt class=
"classname">Event&lt;Arg&gt;</tt> can only be connected to
callbacks derived from <tt class=
"classname">Callback::Function&lt;Arg&gt;</tt>. Clearly, as
<tt class="function">boost::function&lt;&gt;</tt> isn't derived
from this base class it doesn't provide everything we need. And, of
course, it doesn't know how to make the event/callback connection,
either.</p>
<p>So, what about Boost.Signals? Well, yes, we could replace the
whole of our event/callback library with boost::signals, but I'm
reluctant to do that for several (not very good) reasons. First of
all, I don't like the names: &quot;signal&quot; is already used for something
else in Unix operating systems, and &quot;slot&quot; is a truly bizarre word
for a callback function. Secondly, Boost.Signals does more than we
need or want. Specifically, I'm not convinced that a
general-purpose event/callback library should do its own object
lifetime management and, anyway, we couldn't use that feature in
common cases like Exhibit 1. Finally, if we were to use
Boost.Signals the crime would be reduced to a misdemeanour and
there would be little or no motivation for this article!</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e104" id="d0e104"></a>A Promising
Lead</h2>
</div>
<p>The astute reader may have spotted a clue in the first exhibit.
The <tt class="literal">typedef</tt> isn't there just to provide a
reasonably short name for the callback type - it also shows a
template meta-function in action.</p>
<p>A meta-function in C++ is a compile-time analogue of an ordinary
(run-time) function. Well-behaved run-time functions perform an
operation on a set of values supplied as parameters and generate a
new value as their result. Meta-functions typically perform an
operation on a set of types supplied as parameters and generate a
new type as their result.</p>
<p>In its simplest form, a meta-function taking a single type
parameter and returning another type as its result looks like
this:</p>
<div class="sidebar">
<p class="title c3">Exhibit 3: A simple meta-function.</p>
<pre class="programlisting">
template&lt;typename Arg&gt;
struct meta_function {
  typedef &lt;some type expression involving Arg&gt;
       type;
};
</pre></div>
<p>In C++, a meta-function always involves a template. The
metafunction's parameters are the template's parameters and the
metafunction's result is a nested type name or integral constant.
The Boost Meta-Programming Library adopts the convention that a
meta-function's result is called <span class=
"returnvalue">type</span> (if it's a type) or <span class=
"returnvalue">value</span> (if it's an integral constant) and that
same convention is used here.</p>
<p>Now, suppose we had a meta-function that takes a pointerto-
member-function type and returns the function's parameter type.</p>
<div class="sidebar">
<p class="title c3">Exhibit 4: A magical meta-function.</p>
<pre class="programlisting">
template&lt;typename Pmf&gt;
                 // Result (Class::*Pmf)(Arg)
struct argument {
  typedef &lt;magic involving Pmf&gt; type;
                 // type == Arg
};
</pre></div>
<p>Similarly, we can imagine meta-functions that extract from a
pointer-to-member-function the function's result type and the class
of which the function is a member. We could now write a <tt class=
"classname">Bound_Callback&lt;Pmf&gt;</tt> template along the lines
of Exhibit 5.</p>
<div class="sidebar">
<p class="title c3">Exhibit 5: Using a meta-function.</p>
<pre class="programlisting">
// A callback bound to an event.
template&lt;typename Pmf&gt;
class Bound_Callback
  : public Callback::Function&lt;typename argument&lt;Pmf&gt;::type&gt; {
public:
  typedef typename argument&lt;Pmf&gt;::type Arg;
  typedef typename result&lt;Pmf&gt;::type Result;
  typedef typename class_&lt;Pmf&gt;::type Class;
  Bound_Callback(Event&lt;Arg&gt;&amp; event, Pmf f,
                 Class* p)
    : pointer(p), function(f)
    , connection(event, this) {}
  Result operator()(Arg value) {
    return (pointer-&gt;*function)(value);
  }
private:
  Class* pointer;
  Pmf function;
  Callback::Connection&lt;Arg&gt; connection;
};
</pre></div>
<p>This would be exactly what we need to implement the sort of
class illustrated in Exhibit 2. As Sherlock Holmes himself might
say, &quot;Well done, Watson. Now, how can we implement the <tt class=
"function">argument&lt;Pmf&gt;</tt>, <tt class=
"function">result&lt;Pmf&gt;</tt> and <tt class=
"function">class_&lt;Pmf&gt;</tt> metafunctions?&quot;</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e157" id="d0e157"></a>Reviewing the
Evidence</h2>
</div>
<p>The <tt class="function">argument&lt;Pmf&gt;</tt> meta-function
shown in Exhibit 4 works perfectly, but only if your name is Harry
Potter. Plodding detectives (and C++ compilers) can't be expected
to perform magic. I was puzzled. Then I spotted something odd among
the evidence:</p>
<div class="sidebar">
<p class="title c3">Exhibit 6: A meta-function for
clairvoyants.</p>
<pre class="programlisting">
template&lt;typename Result, typename Class,
         typename Arg&gt;
struct argument {
  typedef Arg type;
};
</pre></div>
<p>Here's a meta-function that extracts the parameter type without
using magic. It just needs a little clairvoyance. If you know in
advance what the parameter type is you can use this metafunction to
generate the type you need. The heroic sleuth in detective novels
may seem to be clairvoyant at times but programmers are not that
clever (not even pizza-stuffed, caffeinesoaked <span class=
"emphasis"><em>real</em></span> programmers).</p>
<p>My search for the <tt class="function">argument&lt;Pmf&gt;</tt>
meta-function had run up a blind alley. It was late. I was tired. I
was getting desperate. And then it hit me. We were looking for a
meta-function with one parameter (like the magical one), but to
implement it we need three parameters (like the one for
clairvoyants). We need a <span class=
"emphasis"><em>specialisation</em></span>.</p>
<div class="sidebar">
<p class="title c3">Exhibit 7: Extracting the parameter type.</p>
<pre class="programlisting">
// Declaration of general template
template&lt;typename Pmf&gt; struct argument;
// Partial specialisation for pointers to
// member functions
template&lt;typename Result, typename Class,
         typename Arg&gt;
struct argument&lt;Result (Class::*)(Arg)&gt; {
  typedef Arg type;
};
</pre></div>
<p>The specialisation tells the compiler how to instantiate
<tt class="function">argument&lt;Pmf&gt;</tt> when <i class=
"parameter"><tt>Pmf</tt></i> is a pointer to a member function of
any class, taking a single parameter of any type and returning a
result of any type.</p>
<p>The same technique works for the <tt class=
"function">result&lt;Pmf&gt;</tt> and <tt class=
"function">class_&lt;Pmf&gt;</tt> meta-functions, too. In each
case, the general template takes one parameter, but the
specialisation takes three. The compiler performs a form of pattern
matching to break down a single pointerto- member-function type
into its three components. For example:</p>
<div class="sidebar">
<p class="title c3">Exhibit 8: Using the <tt class=
"function">result&lt;Pmf&gt;</tt> meta-function.</p>
<pre class="programlisting">
typedef result&lt;
        void (Observer::*)(int)&gt;::type Result;
Result* null_pointer = 0;  // Result is void
</pre></div>
<p>When it sees the <tt class="function">result&lt;Pmf&gt;</tt>
template being used the compiler compares the template argument
(pointer-to-member-of-<tt class="classname">Observer</tt>) with the
template parameter of the specialisation (any pointer-tomember-
function). In this case the argument matches the parameter and the
compiler deduces <tt class="literal">Result = void</tt>, <tt class=
"literal">Class = Observer</tt>, <tt class="literal">Arg =
int</tt>. The compiler then instantiates the specialisation which
defines <tt class="literal">result&lt;void
(Observer::*)(int)&gt;::type</tt> as <tt class=
"type">void</tt>.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e235" id="d0e235"></a>The Case is
Closed</h2>
</div>
<p>So that's it. The crime is solved. All that's left is to prepare
a case for presentation in court and let justice take its course.
I've had enough for one day. &quot;I'm off to the pub, anyone want to
join me?&quot;, I called across the office.</p>
<p>&quot;Well, that was the usual warm, friendly response&quot;, I thought,
as I sat on my own with a pint. &quot;No thanks&quot;, &quot;Sorry, can't&quot;, &quot;Too
busy&quot; they said. But something was still bothering me. Does
<tt class="classname">Bound_Callback&lt;Pmf&gt;</tt> still work if
we try to connect a handler function taking an <tt class=
"type">int</tt> to an <tt class="classname">Event</tt> that
publishes a short? And what if we need to connect an <tt class=
"classname">Event&lt;Arg&gt;</tt> to something other than a member
function - like a non-member function or a function object?</p>
<p>These thoughts were still churning over in my mind when,
sometime after midnight, I tumbled into bed and soon fell into a
fitful sleep.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e256" id="d0e256"></a>References</h2>
</div>
<div class="bibliomixed"><a name="Bass" id="Bass"></a>
<p class="bibliomixed">[Bass] Phil Bass, &quot;Implementing the Observer
Pattern in C++&quot;, <span class="citetitle"><i class=
"citetitle">Overload 53</i></span>, February 2003.</p>
</div>
<div class="bibliomixed"><a name="boost" id="boost"></a>
<p class="bibliomixed">[boost] See <span class=
"bibliomisc"><a href="http://www.boost.org" target=
"_top">www.boost.org</a></span></p>
</div>
</div>
<div class="footnotes"><br>
<hr class="c4" width="100">
<div class="footnote">
<p><sup>[<a name="ftn.d0e44" href="#d0e44" id=
"ftn.d0e44">1</a>]</sup> These are not-quite-standard variations of
<tt class="function">std::bind1st()</tt> and <tt class=
"function">std::mem_fun()</tt> developed in-house for reasons that
are not important here.</p>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
