Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ RTTI Viable Examples [closed]

Tags:

c++

rtti

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 ;    } } 
like image 333
paercebal Avatar asked Oct 26 '08 18:10

paercebal


People also ask

Does C have RTTI?

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.

What is RTTI in C++ example?

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.

Does dynamic_cast use RTTI?

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.

Is RTTI slow?

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).


2 Answers

Acyclic Visitor (pdf) is a great use of it.

like image 124
fizzer Avatar answered Oct 08 '22 15:10

fizzer


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<>.

like image 34
Martin York Avatar answered Oct 08 '22 16:10

Martin York