是否在编译时在c ++中评估类型名称的typeid?

cyr*_*42e 4 c++ gcc g++ typeid compile-time

我想检查在编译时使用类型名称(即typeid(int),typeid(std :: string)...)评估typeid.

为此,我在一个循环中重复了两个typeid调用的比较,并在启用了优化的情况下对其进行了编译,以便查看编译器是否简化了循环(通过查看执行时间是1us,当它简化而不是160ms时它不是).

而且我得到了奇怪的结果,因为有时编译器会简化代码,有时则不会.我使用g ++(我试过不同的4.x版本),这是程序:

#include <iostream>
#include <typeinfo>
#include <time.h>

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, &tp1);
    for(int i = 0; i < 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, &tp2);
    std::cout << "time (" << avg << "): " << 
        (tp2.tv_sec-tp1.tv_sec)*1000000000+(tp2.tv_nsec-tp1.tv_nsec) << 
        " ns" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

这个问题出现的条件不明确,但是:
- 如果没有涉及继承,没有问题(总是编译时间)
- 如果我只进行一次比较,没有问题
- 问题只出现在比较分离的情况下所有条款都是假的

那么有什么东西我没有得到typeid如何工作(它是否总是应该在编译时与类型名称一起使用时进行评估?)或者这可能是评估或优化中的gcc错误?

关于上下文,我将问题跟踪到这个非常简单的示例,但我的目标是将typeid与模板类型一起使用(因为部分函数模板不可能专门化).

谢谢你的帮助!

Edw*_*nge 7

我真的不知道你的问题的答案,但如果你使用is_same <> metafunction而不是typeid,你可能会得到更理想的结果.即使您无法访问此元函数,也可以轻松编写一个:


template < typename T1, typename T2 >
struct is_same
{
  enum { value = false }; // is_same represents a bool.
  typedef is_same<T1,T2> type; // to qualify as a metafunction.
};

template < typename T >
struct is_same
{
  enum { value = true };
  typedef is_same<T,T> type;
};
Run Code Online (Sandbox Code Playgroud)