C++のtypeidの用途は何ですか?
C++でのtypeidは、式の型情報を取得するための演算子です。これは、std::type_infoオブジェクトを返し、そのオブジェクトには式の型情報が含まれています。
typeidは通常、dynamic_castとstd::type_infoと一緒に使用され、ランタイムでオブジェクトの実際の型を識別するために多相性を実現します。
以下は、typeidの使い方の例です:
#include <iostream>
#include <typeinfo>
class Base {
virtual void foo() {}
};
class Derived : public Base {};
int main() {
Base* basePtr = new Derived();
// 使用typeid获取basePtr所指对象的类型信息
const std::type_info& type = typeid(*basePtr);
// 打印类型的名称
std::cout << "Object type: " << type.name() << std::endl;
// 使用typeid进行类型判断
if (type == typeid(Base)) {
std::cout << "Object is of type Base" << std::endl;
}
else if (type == typeid(Derived)) {
std::cout << "Object is of type Derived" << std::endl;
}
delete basePtr;
return 0;
}
結果を出力します。
Object type: class Derived
Object is of type Derived
上記の例では、typeid(*basePtr)が返すtype_infoオブジェクトの名前は”class Derived”であり、それはbasePtrが指すオブジェクトの実際の型がDerivedであることを示しています。