文章目錄
- 基本用法
- 編譯時或運行時判定
基本用法
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));
}