Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is using 'typeid' the best solution?

Tags:

c++

typeid

There are many reasons not to use typeid. Other than for using members of type_info (implementation defined behavior), it is usually (always?) possible to provide similar functionality using other C++ language features, eg: overloading, virtual functions etc.

So, excluding usage that relies on the implementation defined behavior, does anybody have a real world example where typeid is the best solution?

like image 559
Richard Corden Avatar asked Jul 19 '11 17:07

Richard Corden


People also ask

What is the use of Typeid?

The typeid operator provides a program with the ability to retrieve the actual derived type of the object referred to by a pointer or a reference. This operator, along with the dynamic_cast operator, are provided for runtime type identification (RTTI) support in C++.

How does Typeid work in C++?

For polymorphic types typeid does indeed return the information about the dynamic type of the expression, i.e. about its run-time type. To implement this something has to be stored inside the actual object at run-time.

What does Typeid name return C++?

typeid( object ); The typeid operator is used to determine the class of an object at runtime. It returns a reference to a std::type_info object, which exists until the end of the program, that describes the "object".

What is Typeinfo C++?

The class type_info holds implementation-specific information about a type, including the name of the type and means to compare two types for equality or collating order. This is the class returned by the typeid operator. The type_info class is neither CopyConstructible nor CopyAssignable.


1 Answers

So, excluding usage that relies on the implementation defined behavior, does anybody have a real world example where typeid is the best solution?

I sometimes use it in debug outputs, to verify that a template argument passed to my function is indeed of a given type. This makes sense in my case since the actual template argument passed to my function is generated by a specialised metafunction and I want to make sure that the right metafunction is used.

like image 195
Konrad Rudolph Avatar answered Sep 30 '22 21:09

Konrad Rudolph