C++: type_info to distinguish types

前端 未结 5 1958
太阳男子
太阳男子 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:09

    You can store it like this.

    class my_type_info
    {
    public:
         my_type_info(const std::type_info& info) : info_(&info){}
         std::type_info get() const { return *info_;}
    private:
         const std::type_info* info_;
    };
    

    EDIT:

    C++ standard 5.2.8.

    The result of a typeid expression is an lvalue of static type const std::type_info...

    Which means you can use it like this.

    my_type_info(typeid(my_type));
    

    The typeid function returns an lvalue (it is not temporary) and therefore the address of the returned type_info is always valid.

提交回复
热议问题