文章目录
- 基本用法
- 编译时或运行时判定
基本用法
typeid 是 C++ 的一个运算符,它用于获取表达式的类型信息。它返回一个 std::type_info 对象引用,该对象包含有关表达式的类型的信息。
要使用 typeid 运算符,需要包含 <typeinfo> 头文件,并使用表达式作为其操作数。通常,可以将变量、对象或类型名称作为表达式。
如果表达式的类型是类类型且至少包含有一个虚函数,则typeid操作符返回表达式的动态类型,需要在运行时计算;
 否则,typeid操作符返回表达式的静态类型,在编译时就可以计算。
ISO C++标准并没有确切定义type_info,它的确切定义编译器相关的,但是标准却规定了其实现必需提供如下四种操作(在之后的章节中我会来分析type_info类文件的源码)
| 运算 | 描述 | 
|---|---|
| t1 == t2 | 如果两个对象t1和t2类型相同,则返回true;否则返回false | 
| t1 != t2 | 如果两个对象t1和t2类型不同,则返回true;否则返回false | 
| t.name() | 返回类型的C-style字符串,类型名字用系统相关的方法产生1 | 
| t1.before(t2) | 返回指出t1是否出现在t2之前的bool值 | 
type_info包含了一个虚析构,因为它通常是作为类型的基类,其实现比较简单:
class type_info {
  
    protected:
    	const char* __name;
    
        explicit type_info(const char* __n) : __name(_n) {}
};
借助了程序内存地址的唯一性来判别两个类型是否相等。
以下是使用 typeid 的示例:
#include <iostream>
#include <typeinfo>
class MyClass {
public:
    int a;
    double b;
};
int main() {
    int num;
    MyClass obj;
    const std::type_info& numType = typeid(num);
    const std::type_info& objType = typeid(obj);
    std::cout << "Type of num: " << numType.name() << std::endl;
    std::cout << "Type of obj: " << objType.name() << std::endl;
    return 0;
}
在上述代码中,我们使用 typeid 运算符分别获取了变量 num 和对象 obj 的类型信息。

编译时或运行时判定
如果对象没有多态性质的话,可以在编译时期就决定它的对象类型:
class Point {
  private:
    int x_;
}
class Point2D : public Point {
  private:
    int y_;
}
int main() {
  Point* p = new Point2D();
  assert(typid(*p) == typeid(Point));
}
对于存在多态的类型,会在运行时判定:
class Point {
  virtual ~Point();
  private:
    int x_;
}
class Point2D : public Point {
  private:
    int y_;
}
int main() {
  Point* p = new Point2D();
  assert(typid(*p) == typeid(Point2D));
}



















