Search code examples
c++vectorpolymorphismreinterpret-caststatic-cast

Cast an entire vector


Is it possible to cast a std::vector<std::shared_ptr<Object>> to an std::vector<std::shared_ptr<SpecializedObject>> where SpecializedObject inherits Object, without building a new array (or iterate through the vector)?


Solution

  • Short answer: no.

    Long answer:

    std::vector<std::shared_ptr<Object>> and std::vector<std::shared_ptr<SpecializedObject>> are completely different and unrelated beasts and you cannot cast from one type to the other one.
    You must iterate through the vector and create a new one from that.

    Hint: you can still use static_pointer_cast to cast the pointers while iterating (if you know what you are doing, of course).