title: Is typeid of type name always evaluated at compile time in c++?
body: <p>I wanted to check that typeid is evaluated at compile time when used with a type name (ie typeid(int), typeid(std::string)...).</p>
  
  <p>To do so, I repeated in a loop the comparison of two typeid calls, and compiled it with optimizations enabled, in order to see if the compiler simplified the loop (by looking at the execution time which is 1us when it simplifies instead of 160ms when it does not).</p>
  
  <p>And I get strange results, because sometimes the compiler simplifies the code, and sometimes it does not. I use g++ (I tried different 4.x versions), and here is the program:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;typeinfo&gt;
  #include &lt;time.h&gt;
  
  class DisplayData {};
  
  class RobotDisplay: public DisplayData {};
  class SensorDisplay: public DisplayData {};
  
  class RobotQt {};
  class SensorQt {};
  
  timespec tp1, tp2;
  const int n = 1000000000;
  
  int main()
  {
      int avg = 0;
      clock_gettime(CLOCK_REALTIME, &amp;tp1);
      for(int i = 0; i &lt; n; ++i)
      {
  //      if (typeid(RobotQt) == typeid(RobotDisplay))    // (1) compile time
  //      if (typeid(SensorQt) == typeid(SensorDisplay))  // (2) compile time
          if (typeid(RobotQt) == typeid(RobotDisplay) || 
              typeid(SensorQt) == typeid(SensorDisplay))    // (3) not compile time ???!!!
              avg++;
          else
              avg--;
      }
      clock_gettime(CLOCK_REALTIME, &amp;tp2);
      std::cout &lt;&lt; "time (" &lt;&lt; avg &lt;&lt; "): " &lt;&lt; 
          (tp2.tv_sec-tp1.tv_sec)*1000000000+(tp2.tv_nsec-tp1.tv_nsec) &lt;&lt; 
          " ns" &lt;&lt; std::endl;
  }
  </code></pre>
  
  <p>The conditions in which this problem appear are not clear, but:<br>
    - if there is no inheritance involved, no problem (always compile time)<br>
    - if I do only one comparison, no problem<br>
    - the problem only appears only with a disjunction of comparisons if all the terms are false</p>
  
  <p>So is there something I didn't get with how typeid works (is it always supposed to be evaluated at compilation time when used with type names?) or may this be a gcc bug in evaluation or optimization?</p>
  
  <p>About the context, I tracked down the problem to this very simplified example, but my goal is to use typeid with template types (as partial function template specialization is not possible).</p>
  
  <p>Thanks for your help!</p>