小编cyr*_*42e的帖子

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

我想检查在编译时使用类型名称(即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) || …
Run Code Online (Sandbox Code Playgroud)

c++ gcc g++ typeid compile-time

4
推荐指数
1
解决办法
2595
查看次数

标签 统计

c++ ×1

compile-time ×1

g++ ×1

gcc ×1

typeid ×1