理解C++运行时类型识别符: typeid

1.  格式

typeid (type-id)

typeid (expression)

typeid 运算符允许在运行时确定对象的类型

typeid 的结果是一个 const type_info&。该值是对 type_info 对象的引用,该对象表示 type-id 或表达式的类型,具体取决于使用哪种形式的 typeid。有关更多信息,请参阅 type_info 类。

typeid 运算符不适用于托管类型(抽象声明符或实例)。

当将 typeid 运算符应用于多态类类型的左值时,它会执行运行时检查,其中对象的真实类型无法通过提供的静态信息确定。此类情况包括:

对类的引用

指针,使用 * 解引用

带下标的指针 ([ ])。(将下标与指向多态类型的指针一起使用是不安全的。)

2.  用法举例

如果表达式指向基类类型,但对象实际上是从该基类派生的类型,则结果为派生类的 type_info 引用。表达式必须指向多态类型(具有virtual函数的类)。否则,结果为表达式中引用的静态类的 type_info。此外,必须解引用指针,以便使用的对象是它指向的对象。如果不解引用指针,结果将是指针的 type_info,而不是它指向的对象。例如:

C++

// expre_typeid_Operator.cpp

// compile with: /GR /EHsc

#include

#include

class Base {

public:

   virtual void vvfunc() {}

};

class Derived : public Base {};

using namespace std;

int main() {

   Derived* pd = new Derived;

   Base* pb = pd;

   cout << typeid( pb ).name() << endl;   //prints "class Base *"

   cout << typeid( *pb ).name() << endl;   //prints "class Derived"

   cout << typeid( pd ).name() << endl;   //prints "class Derived *"

   cout << typeid( *pd ).name() << endl;   //prints "class Derived"

   delete pd;

}

如果表达式是解引用指针,并且该指针的值为零,则 typeid 会抛出 bad_typeid 异常如果指针未指向有效对象,则会抛出 __non_rtti_object 异常。它表示尝试分析触发错误的 RTTI,因为该对象某种程度上无效。(例如,它是一个糟糕的指针,或者代码未使用 /GR 编译)。

如果表达式不是指针,也不是指向对象基类的引用,则结果为表示表达式静态类型的 type_info 引用表达式的静态类型是指编译时已知的表达式类型在评估表达式的静态类型时,将忽略执行语义。此外,在确定表达式的静态类型时,将尽可能忽略引用:

C++

// expre_typeid_Operator_2.cpp

#include

int main()

{

   typeid(int) == typeid(int&); // evaluates to true

}

typeid 也可以在模板中使用来确定模板参数的类型:

C++

// expre_typeid_Operator_3.cpp

// compile with: /c

#include

template < typename T >

T max( T arg1, T arg2 ) {

   cout << typeid( T ).name() << "s compared." << endl;

   return ( arg1 > arg2 ? arg1 : arg2 );

}

你可能感兴趣的:(c++,typeid,运行时类型识别)