typeid 關鍵字

typeid 關鍵字是一元運算子,如果運算元的型別是多型類型別,則會生成有關其運算元的執行時型別資訊。它返回一個 const std::type_info 型別的左值。頂級 cv 資格被忽略。

struct Base {
    virtual ~Base() = default;
};
struct Derived : Base {};
Base* b = new Derived;
assert(typeid(*b) == typeid(Derived{})); // OK

typeid 也可以直接應用於某種型別。在這種情況下,將剝離第一個頂級引用,然後忽略頂級 cv-qualification。因此,上面的例子可能是用 typeid(Derived) 而不是 typeid(Derived{}) 寫的:

assert(typeid(*b) == typeid(Derived{})); // OK

如果 typeid 應用於任何多型類型別的表示式,則不評估運算元,返回的型別資訊用於靜態型別。

struct Base {
    // note: no virtual destructor
};
struct Derived : Base {};
Derived d;
Base& b = d;
assert(typeid(b) == typeid(Base)); // not Derived
assert(typeid(std::declval<Base>()) == typeid(Base)); // OK because unevaluated