Using typeid to get name of derived class

后端 未结 5 1857
孤城傲影
孤城傲影 2021-02-13 21:08

I\'m creating a resource manager that takes in classes derived from the class Resource. My problem is that typeid(..).name() returns the wrong name of the class.

5条回答
  •  不要未来只要你来
    2021-02-13 21:30

    My problem is that typeid(..).name() returns the wrong name of the class.

    typeid(...).name() is only useful for debugging or logging purposes. As http://en.cppreference.com/w/cpp/types/type_info/name says:

    No guarantees are given, in particular, the returned string can be identical for several types and change between invocations of the same program.

    As for your problem,

    How can I make the first typeid statement yield 'Texture' without using type conversions?

    The safest, easiest and most correct way to do this would be to add a virtual name function of your own to Resource:

    virtual std::string name() const = 0;
    

    Then override it in every subclass to return the name of the class.

提交回复
热议问题