title: Circumventing RTTI on legacy code
body: <p>I have been looking for a way to get around the slowness of the dynamic cast type checking. Before you start saying I should redesign everything, let me inform you that the design was decided on 5 years ago. I can't fix all 400,000 lines of code that came after (I wish I could), but I can make some changes. I have run this little test on type identification:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;typeinfo&gt;
  #include &lt;stdint.h&gt;
  #include &lt;ctime&gt;
  
  using namespace std;
  
  #define ADD_TYPE_ID \
      static intptr_t type() { return reinterpret_cast&lt;intptr_t&gt;(&amp;type); }\
      virtual intptr_t getType() { return type(); }
  
  struct Base
  {
      ADD_TYPE_ID;
  };
  
  template &lt;typename T&gt;
  struct Derived : public Base
  {
      ADD_TYPE_ID;
  };
  
  int main()
  {
      Base* b = new Derived&lt;int&gt;();
      cout &lt;&lt; "Correct Type: " &lt;&lt; (b-&gt;getType() == Derived&lt;int&gt;::type()) &lt;&lt; endl; // true
      cout &lt;&lt; "Template Type: " &lt;&lt; (b-&gt;getType() == Derived&lt;float&gt;::type()) &lt;&lt; endl; // false
      cout &lt;&lt; "Base Type: " &lt;&lt; (b-&gt;getType() == Base::type()) &lt;&lt; endl; // false
  
      clock_t begin = clock();
      {
          for (size_t i = 0; i &lt; 100000000; i++)
          {
              if (b-&gt;getType() == Derived&lt;int&gt;::type())
                  Derived &lt;int&gt;* d = static_cast&lt;Derived&lt;int&gt;*&gt; (b);
          }
      }
      clock_t end = clock();
      double elapsed = double(end - begin) / CLOCKS_PER_SEC;
  
      cout &lt;&lt; "Type elapsed: " &lt;&lt; elapsed &lt;&lt; endl;
  
      begin = clock();
      {
          for (size_t i = 0; i &lt; 100000000; i++)
          {
              Derived&lt;int&gt;* d = dynamic_cast&lt;Derived&lt;int&gt;*&gt;(b);
              if (d);
          }
      }
      end = clock();
      elapsed = double(end - begin) / CLOCKS_PER_SEC;
  
      cout &lt;&lt; "Type elapsed: " &lt;&lt; elapsed &lt;&lt; endl;
  
      begin = clock();
      {
          for (size_t i = 0; i &lt; 100000000; i++)
          {
              Derived&lt;int&gt;* d = dynamic_cast&lt;Derived&lt;int&gt;*&gt;(b);
              if ( typeid(d) == typeid(Derived&lt;int&gt;*) )
                  static_cast&lt;Derived&lt;int&gt;*&gt; (b);
          }
      }
      end = clock();
      elapsed = double(end - begin) / CLOCKS_PER_SEC;
  
      cout &lt;&lt; "Type elapsed: " &lt;&lt; elapsed &lt;&lt; endl;
  
     return 0;
  }
  </code></pre>
  
  <p>It seems that using the class id (first times solution above) would be the fastest way to do type-checking at runtime.
  Will this cause any problems with threading? Is there a better way to check for types at runtime (with not much re-factoring)?</p>
  
  <p><strong>Edit:</strong>  Might I also add that this needs to work with the TI compilers, which currently only support up to '03</p>