Search code examples
c++typeid

When is using 'typeid' the best solution?


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?


Solution

  • boost::any uses typeid to implement any_cast.

    template<typename T> any_cast(const any& other) {
       if(typeid(T) != other.type()) throw bad_any_cast();
    
       //...actual cast here...
    }
    

    You can't be sure T is polymorphic, so dynamic_cast is out of the question, and the enclosed type within the boost::any call is lost by now, so none of the other casts can provide any sort of type safety.