title: Eliminating recursive template instantiation in C++
body: <p>I want to define a macro that can be invoked in different places (at file scope) in order to create functions that do something.  (In the example below the functions just print a message, but of course my real intent is to do some other useful stuff.)  The challenge is that I want some "manager" function (in my example it will just be <code>main()</code>) to somehow succeed in getting them all invoked (in any order) without any of the code being dependent on the macro invocations (except for the macro invocations themselves, of course).  What I mean is that once the file is written, another programmer would be able to just insert a few new macro invocations at various places or delete some of the existing invocations, and the code would still work without any further change.  I realize this can be done using static objects but I want to explore a different approach.  I'm going to use some template trickery and the fact that <code>__LINE__</code> is monotone increasing.</p>
  
  <pre><code>#include &lt;iostream&gt;
  using namespace std;
  
  template&lt;int i&gt;
  inline void f()
  {
     f&lt;i-1&gt;();
  }
  
  #define START_REGISTRATION                                \
  template&lt;&gt;                                                \
  inline void f&lt;__LINE__&gt;() {}  /* stop the recursion */    \
  template&lt;&gt; void f&lt;__LINE__&gt;()  /* force semicolon */
  
  #define REGISTER(msg)                                     \
  template&lt;&gt;                                                \
  inline void f&lt;__LINE__&gt;()                                 \
  {                                                         \
     cout &lt;&lt; #msg &lt;&lt; endl;                                  \
     f&lt;__LINE__ - 1&gt;();                                     \
  }                                                         \
  template&lt;&gt; void f&lt;__LINE__&gt;()  /* force semicolon */
  
  // Unrelated code ...
  
  START_REGISTRATION;
  
  // Unrelated code ...
  
  REGISTER(message 1);
  
  // Unrelated code ...
  
  REGISTER(message 2);
  
  // Unrelated code ...
  
  REGISTER(message 3);
  
  // Unrelated code ...
  
  // manager function (in this case main() )
  int main()
  {
     f&lt;__LINE__&gt;();
  }
  </code></pre>
  
  <p>This prints</p>
  
  <pre><code>message 3
  message 2
  message 1
  </code></pre>
  
  <p>as expected.</p>
  
  <p>This solution has a few drawbacks.</p>
  
  <ol>
  <li>Can't invoke <code>REGISTER</code> twice on the same line.</li>
  <li>Will break if <code>#line</code> is played with.</li>
  <li>Need to put the manager after all invocations of <code>REGISTER</code>.</li>
  <li>Increased compile time due to the recursive instantiations.</li>
  <li>Unless the "dummy" instantiations of <code>f</code> are all inlined away, the call-stack depth at runtime will be as great as the number of lines between <code>START_REGISTRATION;</code> and  <code>f&lt;__LINE__&gt;();</code> in the manager.</li>
  <li>Code bloat: unless the "dummy" instantiations of <code>f</code> are all inlined away, the number of instantiations will similarly be be as great.</li>
  <li>The excessive instantiation recursion depth is likely to hit the compiler's limit (500 by default on my system).</li>
  </ol>
  
  <p>Issues 1-4 I don't really mind.  Issue 5 can be eliminated by having each function return a pointer to the previous one, and having the manager use these pointers to call the functions iteratively rather than having them call each other.  Issue 6 can be eliminated by creating a similar class template construct that is able to compute for each invocation of <code>REGISTER</code> what function was instantiated in the previous invocation and thus only instantiate the functions that actually do something.  The excessive instantiation will then be shifted from the function template to the class template, but the class instantiations would only tax the compiler; they wouldn't trigger any code generation.  So my real concern is Issue 7, and the question is: is there a way to restructure things so that the compiler does the instantiations iteratively rather than recursively.  I am also open to different approaches altogether (apart from those involving static objects).  One simple solution is to group all registrations together right before the manager (or add a <code>STOP_REGISTRATION</code> macro to end the block of registrations) but that would defeat a significant part of my purpose (registering stuff next to the code that defines it).</p>
  
  <p><strong>Edit:</strong>  There have been some interesting suggestions, but I'm afraid I wasn't making myself clear in terms of what I hope to achieve.  I'm really interested in two things: solving the problem as posed (i.e., no statics, single line per registration, no additional changes when adding/removing registrations, and, although I neglected to say so, only standard C++ --- hence, no boost).  As I said in the comments below, my interest is more theoretical in nature: I'm hoping to learn some new techniques.  Hence, I would really like to focus on restructuring things so the recursion is eliminated (or at least reduced) or finding a different approach that satisfies the constraints I laid out above.</p>
  
  <p><strong>Edit 2:</strong>  MSalter's solution is a large step forward.  At first I thought that every registration would incur the full cost of lines up to it, but then I realized that of course a function can be instantiated only once, so in terms of instantiations we pay the same price as in linear search, but the recursion depth becomes logarithmic.  If I get around to it, I'll post a full solution eliminating Issues 5-7.  It would still be nice, though, to see if it can be done in constant recursion depth, and best, with the number of instantiations linear in the number of invocations (a-la the boost solution).</p>
  
  <p><strong>Edit 3:</strong>  Here's the full solution.</p>
  
  <pre><code>#define START_REGISTRATION                                          \
  template&lt;int lo, int hi&gt;                                            \
  struct LastReg {                                                    \
    enum {                                                            \
       LINE_NUM = LastReg&lt;(lo + hi)/2 + 1, hi&gt;::LINE_NUM ?            \
          static_cast&lt;int&gt;(LastReg&lt;(lo + hi)/2 + 1, hi&gt;::LINE_NUM) :  \
          static_cast&lt;int&gt;(LastReg&lt;lo, (lo + hi)/2&gt;::LINE_NUM)        \
    };                                                                \
  };                                                                  \
  template&lt;int l&gt;                                                     \
  struct LastReg&lt;l, l&gt; {                                              \
     enum { LINE_NUM = 0 };                                           \
  };                                                                  \
  template&lt;int l&gt;                                                     \
  struct PrevReg {                                                    \
     enum { LINE_NUM = LastReg&lt;__LINE__ + 1, l - 1&gt;::LINE_NUM };      \
  };                                                                  \
  template&lt;int l&gt; void Register() {}                                  \
  template&lt;int l&gt; void Register()  /* force semicolon */
  
  
  #define REGISTER(msg)                                               \
  template&lt;&gt;                                                          \
  struct LastReg&lt;__LINE__, __LINE__&gt; {                                \
     enum { LINE_NUM = __LINE__ };                                    \
  };                                                                  \
  template&lt;&gt;                                                          \
  void Register&lt;__LINE__&gt;()                                           \
  {                                                                   \
     cout &lt;&lt; __LINE__ &lt;&lt; ":" &lt;&lt; #msg &lt;&lt; endl;                         \
     Register&lt;PrevReg&lt;__LINE__&gt;::LINE_NUM&gt;();                         \
  }                                                                   \
  template&lt;&gt; void Register&lt;__LINE__&gt;()  /* force semicolon */
  
  
  #define END_REGISTRATION                                            \
  void RegisterAll()                                                  \
  {                                                                   \
     Register&lt;PrevReg&lt;__LINE__&gt;::LINE_NUM&gt;();                         \
  }                                                                   \
  void RegisterAll()  /* force semicolon */
  
  
  START_REGISTRATION;
  
  REGISTER(message 1);
  
  REGISTER(message 2);
  
  END_REGISTRATION;
  
  
  int main()
  {
     RegisterAll();
  }
  </code></pre>