When is using 'typeid' the best solution?

后端 未结 6 446
没有蜡笔的小新
没有蜡笔的小新 2021-01-01 10:16

There are many reasons not to use typeid. Other than for using members of type_info (implementation defined behavior), it is usually (always?) pos

6条回答
  •  我在风中等你
    2021-01-01 10:59

    boost::any uses typeid to implement any_cast.

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

提交回复
热议问题