Best Practice For List of Polymorphic Objects in C++

前端 未结 4 1841
执念已碎
执念已碎 2020-12-19 11:25

What is a common practice for the storage of a list of base class pointers each of which can describe a polymorphic derived class?

To elaborate and in the interest o

4条回答
  •  执笔经年
    2020-12-19 11:51

    I would propose boost::shared_pointer in an STL container. Then use dynamic_cast to downcast guarantee type correctness. If you want to provide helper functions to toss exceptions instead of returning NULL, then follow Alex's suggestion and define a template helper function like:

    template 
    T* downcast_to(U *inPtr) {
        T* outPtr = dynamic_cast(inPtr);
        if (outPtr == NULL) {
            throw std::bad_cast("inappropriate cast");
        }
        return outPtr;
    }    
    

    and use it like:

    void some_function(Shape *shp) {
        Circle *circ = downcast_to(shp);
        // ...
    }
    

    Using a separate class like GenericShape is just too strongly coupled with every class that descends from Shape. I wonder if this would be considered a code smell or not...

提交回复
热议问题