C++: type_info to distinguish types

前端 未结 5 1968
太阳男子
太阳男子 2021-02-01 20:20

I know that compilers have much freedom in implementing std::type_info functions\' behavior.

I\'m thinking about using it to compare object types, so I\'d l

5条回答
  •  爱一瞬间的悲伤
    2021-02-01 21:07

    Standard 18.5.1 (Class type_info) :

    The class type_info describes type information generated by the implementation. Objects of this class effectively store a pointer to a name for the type, and an encoded value suitable for comparing two types for equality or collating order. The names, encoding rule, and collating sequence for types are all unspecified and may differ between programs.

    From my understanding :

    1. You don't have this guarantee regarding std:type_info::name. The standard only states that name returns an implementation-defined NTBS, and I believe a conforming implementation could very well return the same string for every type.
    2. I don't know, and the standard isn't clear on this point, so I wouldn't rely on such behavior.
    3. That one should be a definite 'Yes' for me
    4. That one should be a definite 'Yes' for me

    Regarding the second set of questions :

    • No, you cannot store a type_info. Andrei Alexandrescu proposes a TypeInfo wrapper in its Modern C++ Design book. Note that the objects returned by typeid have static storage so you can safely store pointers without worrying about object lifetime
    • I believe you can assume that type_info comparison are extremely efficient (there really isn't much to compare).

提交回复
热议问题