When is using 'typeid' the best solution?

Richard Corden picture Richard Corden · Jul 19, 2011 · Viewed 8.1k times · Source

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?

Answer

Konrad Rudolph picture Konrad Rudolph · Jul 19, 2011

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.