Home >Backend Development >C++ >How to handle runtime type information in C++ generic programming?
In C++ generic programming, two methods are provided for handling run-time type information (RTTI): The dynamic_cast operator is used to convert a base class pointer or reference to a derived class pointer or reference. The typeid operator returns the type information of an object, and the type name can be obtained through its name() member function. RTTI, while convenient, incurs additional overhead and is therefore only recommended when needed, keeping in mind the binary compatibility issues it may cause.
Handling runtime type information (RTTI) in C++ generic programming
In C++ generic programming, we often need Gets type information for an object or reference variable at runtime. C++ provides a runtime type information (RTTI) mechanism for this purpose.
Using dynamic_cast
The dynamic_cast
operator is used to convert a base class pointer or reference to a derived class pointer or reference. If the conversion is successful, it returns a pointer or reference to the derived class; otherwise, it returns nullptr
.
class Base { }; class Derived : public Base { }; int main() { Base* base_ptr = new Derived(); // 检查 base_ptr 是否指向 Derived 对象 Derived* derived_ptr = dynamic_cast<Derived*>(base_ptr); if (derived_ptr != nullptr) { // 转换成功,base_ptr 指向 Derived 对象 } }
Use typeid
typeid
operator to return the type information of the object, which is a std::type_info
Object. You can use the name()
member function to obtain the type name, and you can use the before()
and after()
member functions to compare types.
class Base { }; class Derived : public Base { }; int main() { Base obj; std::cout << typeid(obj).name() << std::endl; // 输出:Base // 检查 obj 是否属于 Derived 类型 if (typeid(obj).before(typeid(Derived))) { std::cout << "obj is not a Derived object" << std::endl; } }
Notes on using RTTI
Practical case
Scenario:There is a set of shapes (such as circles, rectangles and triangles) that need to be executed differently according to their types operation.
Code:
class Shape { public: virtual void draw() = 0; }; class Circle : public Shape { public: void draw() override { std::cout << "Drawing a circle" << std::endl; } }; class Rectangle : public Shape { public: void draw() override { std::cout << "Drawing a rectangle" << std::endl; } }; class Triangle : public Shape { public: void draw() override { std::cout << "Drawing a triangle" << std::endl; } }; int main() { std::vector<Shape*> shapes{new Circle, new Rectangle, new Triangle}; for (auto shape : shapes) { // 使用 RTTI 获取形状类型 std::cout << "Drawing a " << typeid(*shape).name() << std::endl; // 根据类型调用相应的方法 shape->draw(); } }
Output:
Drawing a Circle Drawing a Rectangle Drawing a Triangle
The above is the detailed content of How to handle runtime type information in C++ generic programming?. For more information, please follow other related articles on the PHP Chinese website!