typeid是c++的一個關鍵字,typeid操作符的返回結果是標準庫類型type_info對象的引用。
但是,C++標準並沒有明確定義type_info,其具體實現依賴於各個編譯器。標準只規定了typeid操作符必需實現如下四種操作:
操作 | 說明 |
---|---|
t1 == t2 | 如果兩個對象t1和t2類型相同,則返回true;否則返回false |
t1 != t2 | 如果兩個對象t1和t2類型不同,則返回true;否則返回false |
t.name() | 返回類型的C-style字符串。由編譯器決定,不一定就是真實的類型名 |
t1.before(t2) | 判斷t1是否位於t2的前面。類型排列順序與編譯器相關,基類不一定位於派生類的前面。 |
type_info的成員函數name返回類型的C-style字符串,但這個返回的類型名與程序中使用的相應類型名不一定一致,其返回值的實現由編譯器決定,標準只要求每個類型返回的字符串是唯一的。
和sizeof操作符類似,typeid的操作對象既可以是數據類型,也可以是表達式。
使用typeid判斷各種類型示例代碼如下:
#include<iostream>
#include <typeinfo>
using namespace std;
class Base{};
class Derived:public Base{};
void func1();
int func2(int n);
int main()
{
int a = 10;
int* b = &a;
float c;
double d;
cout << typeid(a).name() << endl;
cout << typeid(b).name() << endl;
cout << typeid(c).name() << endl;
cout << typeid(d).name() << endl;
cout << typeid(Base).name() << endl;
cout << typeid(Derived).name() << endl;
cout << typeid(func1).name() << endl;
cout << typeid(func2).name() << endl;
}
- Mac下使用clang++編譯運行結果如下:
i
Pi
f
d
4Base
7Derived
FvvE
FiiE
- 不像Java、C#等動態語言,C++運行時能獲取到的類型信息非常有限,標準也定義的很模糊,如同“雞肋”一般。在實際工作中,我們一般只使用type_info的“==”運算符來判斷兩個類型是否相同。
- 再來看看下面的示例代碼:
#include<iostream>
#include <typeinfo>
using namespace std;
class Base{};
class Drived: public Base{};
int main()
{
Base* pb;
Drived d;
pb = &d;
if(strcmp(typeid(*pb).name(), typeid(Base).name()) == 0)
{
cout << "this is Base" << endl;
}
else if(strcmp(typeid(*pb).name(), typeid(Drived).name()) == 0)
{
cout << "this is Drived" << endl;
}
if(strcmp(typeid(d).name(), typeid(Base).name()) == 0)
{
cout << "this is Base" << endl;
}
else if(strcmp(typeid(d).name(), typeid(Drived).name()) == 0)
{
cout << "this is Drived" << endl;
}
}
- Mac下使用clang++編譯運行結果如下:
this is Base
this is Drived
- 從運行結果中可以看出,即使用基類指針指向派生類,但使用typeid判斷的基類指針類型依然是基類指針。因此我們不能用typeid來判斷基類指針實際指向的是否是某個派生類。