I am familiar with C++ RTTI, and find the concept interesting.
Still there exist a lot of more ways to abuse it than to use it correctly (the RTTI-switch dread comes to mind). As a developer, I found (and used) only two viable uses for it (more exactly, one and a half).
Could you share some of the ways RTTI is a viable solution to a problem, with example code/pseudo-code included?
Note: The aim is to have a repository of viable examples a junior developer can consult, criticize and learn from.
Edit: You'll find below code using C++ RTTI
// A has a virtual destructor (i.e. is polymorphic) // B has a virtual destructor (i.e. is polymorphic) // B does (or does not ... pick your poison) inherits from A void doSomething(A * a) { // typeid()::name() returns the "name" of the object (not portable) std::cout << "a is [" << typeid(*a).name() << "]"<< std::endl ; // the dynamic_cast of a pointer to another will return NULL is // the conversion is not possible if(B * b = dynamic_cast<B *>(a)) { std::cout << "a is b" << std::endl ; } else { std::cout << "a is NOT b" << std::endl ; } }
Overview. In C++, RTTI can be used to do safe typecasts, using the dynamic_cast<> operator, and to manipulate type information at runtime, using the typeid operator and std::type_info class.
Run-time type information (RTTI) is a mechanism that allows the type of an object to be determined during program execution. RTTI was added to the C++ language because many vendors of class libraries were implementing this functionality themselves.
For example, dynamic_cast uses RTTI and the following program fails with the error “cannot dynamic_cast `b' (of type `class B*') to type `class D*' (source type is not polymorphic) ” because there is no virtual function in the base class B.
tl;dr: RTTI in GCC uses negligible space and typeid(a) == typeid(b) is very fast, on many platforms (Linux, BSD and maybe embedded platforms, but not mingw32).
Acyclic Visitor (pdf) is a great use of it.
How about the boost::any object!
This basically uses the RTTI info to store any object and the retrieve that object use boost::any_cast<>.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With