typeid 運算符
- 查詢類型的信息。
- 用於必須知曉多態對象的動態類型的場合以及靜態類型鑒別。
- 語法
(1) typeid( 類型 )
(2) typeid( 表達式 ) - typeid 表達式為左值表達式,指代一個具有靜態存儲期的,多態類型 或某個其派生類型的const std::type_info 對象。
- 類 type_info 指定一個類型的信息,包括類型的名稱和比較二個類型相等的方法。這是 typeid 運算符所返回的類。
- 獲取完整類型名方法:typeid(類型名/表達式).name()
#include <iostream>
#include <string>
#include <typeinfo>
struct Base {}; // 非多態
struct Derived : Base {};
struct Base2 { virtual void foo() {} }; // 多態
struct Derived2 : Base2 {};
int main() {
int myint = 50;
std::string mystr = "string";
double *mydoubleptr = nullptr;
std::cout << "myint has type: " << typeid(myint).name() << '\n'
<< "mystr has type: " << typeid(mystr).name() << '\n'
<< "mydoubleptr has type: " << typeid(mydoubleptr).name() << '\n';
// std::cout << myint 為多態類型的泛左值表達式;求值
const std::type_info& r1 = typeid(std::cout << myint);
std::cout << '\n' << "std::cout<<myint has type : " << r1.name() << '\n';
// std::printf() 不是多態類型的泛左值表達式;不求值
const std::type_info& r2 = typeid(std::printf("%d\n", myint));
std::cout << "printf(\"%d\\n\",myint) has type : " << r2.name() << '\n';
// 非多態左值時為靜態類型
Derived d1;
Base& b1 = d1;
std::cout << "reference to non-polymorphic base: " << typeid(b1).name() << '\n';
Derived2 d2;
Base2& b2 = d2;
std::cout << "reference to polymorphic base: " << typeid(b2).name() << '\n';
try {
// 解引用空指針:對於非多態表達式 OK
std::cout << "mydoubleptr points to " << typeid(*mydoubleptr).name() << '\n';
// 解引用空指針:對多態左值則不行
Derived2* bad_ptr = nullptr;
std::cout << "bad_ptr points to... ";
std::cout << typeid(*bad_ptr).name() << '\n';
} catch (const std::bad_typeid& e) {
std::cout << " caught " << e.what() << '\n';
}
}
可能的輸出:
myint has type: int
mystr has type: std::basic_string<char, std::char_traits<char>, std::allocator<char> >
mydoubleptr has type: double*
50
std::cout<<myint has type : std::basic_ostream<char, std::char_traits<char> >
printf("%d\n",myint) has type : int
reference to non-polymorphic base: Base
reference to polymorphic base: Derived2
mydoubleptr points to double
bad_ptr points to... caught std::bad_typeid
