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