When is using 'typeid' the best solution?

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

    Write a dynamic tree where you can on the runtime modify structure of the tree where there are different types in each link, it'll need typeid. dynamic_cast is not enough.

    Edit: Here's some details:

    class I {
    public:
       virtual std::string type() const=0;
       virtual void *value() const=0;
    };
    template
    class Impl : public I
    {
    public:
        Impl(T t) : t(t) { }
        std::string type() const { return typeid(T).name(); }
        void *value() const { return &t; }
    private:
        T t;
    };
    

    And then build a tree out of these:

    template
    class Tree { };
    

    With link type being the I* interface... Since the above works for any values of type T1,T2,T3,T4, we could also with similar classes for any functions T->T1, T->T2, T->T3, T->T4, and use that function type as the Node of the tree. Now you have proper expressions described in dynamic tree.

提交回复
热议问题