    <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  :: Where is __FUNCTION__?</title>
        <link>https://members.accu.org/index.php/articles/462</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 #41 - Feb 2001</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/c163/">41</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c65+163/">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;Where is __FUNCTION__?</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 February 2001 16:46:05 +00:00 or Mon, 26 February 2001 16:46:05 +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>Most C/C++ programmers have likely made use of the <tt class=
"literal">__FILE__</tt> and <tt class="literal">__LINE__</tt>
macros in their source files. They are provided by C/C++ compilers
for outputting the file and line number of a particular line of
code, usually for debugging purposes. I use this a lot with
exceptions targeted at trapping bugs. For instance:</p>
<pre class="programlisting">
class BugException {
  public:
    BugException(const string&amp; mm,     const string&amp; ff, int ll):
       msg(mm), file(ff), line(ll) {}
    const string msg;
    const string file;
    const int line;
};
</pre>
<p>which I can use as:</p>
<pre class="programlisting">
void doSomething() {
  // ... fail some bug-trapping test
  throw BugException(&quot;i should be &gt; j&quot;,
                 __FILE__, __LINE__);
}
int main() {
  try { doSomething(); } 
  catch (BugException&amp; be) {
    cerr &lt;&lt; &quot;*** Bug: &quot; &lt;&lt; be.msg 
        &lt;&lt; &quot; at file &quot; &lt;&lt; be.file     &lt;&lt; &quot;, line &quot; &lt;&lt; be.line &lt;&lt; endl;
  }
}
</pre>
<p>One type of debugging info that I often wish the compiler
provided is the name of the function or method to which a line of
code belongs, something that might be called <tt class=
"literal">__FUNCTION__</tt>:</p>
<pre class="programlisting">
class Foo {
  public:
    Void bar() {
      cout &lt;&lt; &quot;Inside method &quot; 
          &lt;&lt; __FUNCTION__ &lt;&lt; endl;
    }
};
</pre>
<p>with the following output: &quot;Inside method void Foo::bar()&quot;. This
would be handy when one needs to verify, say, the calling order of
some functions or methods, or to check that some methods are or are
not called. It is not always practical to use debuggers since this
most often requires tedious settings of breakpoints, button
presses, etc. instead of just running the program in debug mode,
and examining the output.</p>
<p>The only compiler that seems to offer this kind of macro is gcc.
For those unfortunates among us who do not get to use open source
compilers such as gcc, there is no way of getting the compiler to
generate the output of <tt class="literal">__FUNCTION__</tt>
automatically. Instead, I have had to resort to tricks like</p>
<pre class="programlisting">
#include &quot;Foo.h&quot;
void Foo::bar(int a) const {
  cout &lt;&lt; &quot;In method Foo::bar(int) const&quot;
      &lt;&lt; endl;
  // do stuff ...
}
</pre>
<p>Replacing the <tt class="literal">Foo::</tt> part of the debug
output with a call to <tt class="literal">typeid(*this).name()</tt>
does not improve the matter much: it is starting to look messy,
requires even more typing, and it is not the class name that
changes most often, but the method signature itself, including the
method's name. I discovered the hard way that good will and
vigilance were not enough: the debug info rapidly gets out of sync
with the actual class interface, especially when the software is
reviewed, extended or debugged. No big deal but has lead to some
confusion.</p>
<p>After posting a question about this to the ACCU-general mailing
list and getting several interesting answers, it was clear that
there was no real support for this kind of debugging information,
and I would have to design my own. But it was also clear, using
bits and pieces mentioned in several posts, mixed in with a little
OOD, that a pretty decent, if not perfect, solution was within
reach.</p>
<p>The essence is to use <tt class="literal">typeid()</tt> on the
function or method pointer, something first suggested by Jon
Jagger. The pitfall is that you need to make a few substitutions in
its output before you can really get something useful. The above
example becomes (I define <tt class="literal">TypeID</tt>
later)</p>
<pre class="programlisting">
// #include &quot;Foo.h&quot;
void Foo::bar(int a) const {
  cout &lt;&lt; &quot;In method &quot; 
      &lt;&lt; TypeID::fn(bar, &quot;bar&quot;) &lt;&lt; endl;
  // ...
}
</pre>
<p>The onus is still on me to keep the second argument in sync with
the function/method name (the compiler will notify me if the first
one does not correspond to a function/method), but this is clearly
far less work that having to worry about the whole function/method
declaration. It is also fairly concise and clear.</p>
<p>There are many possible ways of implementing <tt class=
"literal">TypeID</tt> so I will only discuss one possibility. I
implemented <tt class="literal">TypeID</tt> as a namespace that
groups and provides type information functionality. I first
implemented it as a class with <tt class="literal">static</tt>
methods, with some of the methods as <tt class=
"literal">inline</tt> and <tt class="literal">private</tt> to hide
some implementation details. However given the context of use
(debugging), inlining is not really important, and I was hoping to
avoid having to create temporary objects, so I ended up
implementing it as a <tt class="literal">namespace</tt>. In this
case, <tt class="literal">static</tt> methods are no longer
necessary, (they become merely functions), neither are visibility
qualifiers, and this probably reflects better the fact that no
member data is involved.</p>
<p>The header file for <tt class="literal">TypeID</tt> is
simply:</p>
<pre class="programlisting">
// file TypeID.hh
namespace TypeID {
  template &lt;typename T&gt;
  std::string fn(const T&amp; ptr, 
      const std::string&amp; name);
}
</pre>
<p>whereas the source file hides the implementation details:</p>
<pre class="programlisting">
// file TypeID.cc
#include &lt;typeinfo&gt;
namespace TypeID {
  template &lt;typename T&gt;
  std::string fn(const T&amp; fptr, 
          const std::string&amp; name) {
    std::string fsignature =
                 typeid(fptr).name();
    simplify(fsignature);
    return insertName(fsignature, name);
  }
  void simplify(std::string&amp; fs) {
    // do simplifications like
fs.replace(&quot;basic_string&lt;...&gt;&quot;, &quot;string&quot;);
  }
  std::string insertName(
    std::string&amp; fsig, 
        const std::string&amp; fname);
}
std::string&amp;
TypeID::insertName(std::string&amp; routine,
     const std::string&amp; name){
  int i = routine.find_first_of('(');
  if (i &gt;= routine.size()) // probably 
                    // not a function
    return routine;
  routine.replace(i, 1, &quot; &quot;);
  i = routine.find_first_of('*', i);
  routine.replace(i, 1, name);
  i = routine.find_first_of(')');
  return routine.erase(i, 1);
}
</pre>
<p>The <tt class="function">fn</tt> routine consists, quite simply,
of three steps: get the signature of the function pointer passed as
first argument; simplify it; and finally, insert the function name
given as second argument. The latter is done by <tt class=
"function">insertName</tt>, which has to find where to put the name
in the signature. The rule I have used is to find the first '*'
after the first left parenthesis. I really do not know how
universal this is. Therefore, <tt class="function">insertName</tt>
may have to be modified slightly for different compilers (so maybe
<tt class="literal">TypeID</tt> should be a class after all and the
method made <tt class="literal">virtual</tt>).</p>
<p>The simplification step is fairly important due to the very long
names that can be produced when STL types appear as arguments to
the function/method given as first parameter to <tt class=
"function">TypeID::fn</tt>. Clearly, <tt class=
"function">simplify</tt> will vary depending on your application,
on personal preferences, and so forth. In the above code sample, I
used a line of pseudocode to represent one possible type of
simplification that could occur. Again, customizing the simplify
routine might be a good enough reason to implement <tt class=
"literal">TypeID</tt> as a class.</p>
<p>Finally, it is interesting to note that no check is done on what
is passed to <tt class="function">TypeID::fn</tt>. It could be
given a pointer to a method <span class=
"emphasis"><em>or</em></span> an object, it would still chug away
without complaining, but probably produce meaningless output.
Again, given the context of use (debugging), worrying about this
level of detail is probably overkill.</p>
<p>There are many ways that this could be extended or improved.
Having a class with virtual functions for <tt class=
"function">simplify</tt> and <tt class="function">insertName</tt>
would allow for easier customisation, though it would require
creating an object. In addition, methods/routines could be added
that split the function signature into several parts and makes each
available separately. With a class instead of namespace, you could
do things like:</p>
<pre class="programlisting">
// #include &quot;Foo.h2&quot;
void Foo::bar(int a) const {
  static const TypeID_sgi method(bar, &quot;bar&quot;);
  cout &lt;&lt; &quot;In method &quot; &lt;&lt; method.name() 
&lt;&lt; &quot;\nMethod parameters &quot; &lt;&lt; method.params() &lt;&lt; endl;
  // ...
}
</pre>
<p>where <tt class="literal">TypeID_sgi</tt> is, hypothetically, a
subclass of TypeID customised for SGI's MipsPro compiler.</p>
<p>If others have any suggestions for improvement or ideas for
alternatives, I would be happy to hear from you.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e159" id=
"d0e159"></a>Acknowledgements</h2>
</div>
<p>I would like to thank all those who answered my email question
on the ACCU-general mailing list, and in particular Jon Jagger's
suggestion about <tt class="literal">typeid</tt>, which opened up
some interesting possibilities.</p>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
