When is using 'typeid' the best solution?

后端 未结 6 425
没有蜡笔的小新
没有蜡笔的小新 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:43

    I use it to probe the class type of the exception in my catch all handler.

    // fudge vtable existence (thrown exceptions must have one)
    class StubException
    {
        virtual ~StubException();
    };
    
    .....
    
    catch(...)
    {
        StubException *e = getExceptionObject(); // compiler/rt specific
        std::string s = typeid(e).name();
    
        ...
    
        throw;
    }
    

    The function getExceptionObject() is part of a small utility library I wrong to access additional information about exceptions. It comes in very handy when a function throws an exception I should be catch but don't. It has definitely saved a lot of frustration over the years since I immediately know the type of exception that needs coverage.

提交回复
热议问题