0. typeid与type_info
typeid是实现 运行时类型识别(run-time type identification, RTTI)功能的方法之一,另一个是dynamic_cast。
typeid的返回结果是type_info类型,type_info类型定义在头文件typeinfo中。
1. typeid
typeid使用起来,和decltype差不多。不过decltype返回的是静态类型,typeid可以返回动态类型。
1.1 使用方法
typeid(expr)
expr可以是任意表达式或类型名。
注意:
- 当expr不是类类型或不包含虚函数时,返回e的静态类型
- 当expr是包含了虚函数的类的左值时,在程序运行时才会得到结果,即动态类型
- typeid会忽略顶层const
- typeid + 引用,返回引用源类型
- typeid + 数组,返回数组类型
- typeid + 函数名,返回函数类型
1.2 示例
Derived *derived_ptr = new Derived();
Base *base_ptr = derived_ptr;
// 二者指向同一个对象
if (typeid(*base_ptr) == typeid(*derived_ptr)) {
cout << "二者动态类型相同" << endl;
}
if (typeid(*base_ptr) == typeid(Derived)) {

最低0.47元/天 解锁文章
836





