RTTI 組件
dynamic_cast<T>(ptr):安全向下/橫向轉型,失敗回傳 nullptr(指標)或拋出 bad_cast(參考)。需多態基類別(含虛擬函式)。
typeid(expr):回傳 const std::type_info&,可比較型別、取得名稱(.name(),實作定義字串)。
程式碼
/* test.cpp
* Created on: 2014.04.22
* Author: Spike
*/
#include <iostream>
#include <typeinfo>
using namespace std;
class Base { public: virtual void fcnA() { cout << "base" << endl; } };
class Derived : public Base { public: virtual void fcnB() { cout << "derived" << endl; } };
void fcnC(Base* p) {
if (Derived* dp = dynamic_cast<Derived*>(p)) dp->fcnB();
else p->fcnA();
}
void fcnD(Base* p) {
if (typeid(*p) == typeid(Derived)) {
dynamic_cast<Derived*>(p)->fcnB();
} else p->fcnA();
}
int main() {
Base* cp = new Derived;
cout << typeid(cp).name() << endl; // P4Base (指標型別)
cout << typeid(*cp).name() << endl; // 7Derived (物件動態型別)
cout << typeid(&*cp).name() << endl; // P4Base
fcnC(cp); fcnD(cp);
Base* dp = new Base;
fcnC(dp); fcnD(dp);
}
輸出
P4Base
7Derived
P4Base
derived
derived
base
base
最佳實務
- 優先使用虛擬函式多態,避免 RTTI(開銷、耦合)。
- 需 RTTI 時,
dynamic_cast 比 typeid 更安全(自動空指標檢查)。
- 關閉 RTTI(
-fno-rtti / /GR-)可減小二進位體積,但無法使用 dynamic_cast、typeid、std::type_info。