Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Consider Vector of Child Pointers as Vector of Base Pointers

Suppose there are the following classes:

class A {

};

class B: public A {

};

and the vector of unique_ptr to B:
std::vector<std::unique_ptr<B>> bElements
Is there a possibility to pass the vector to a function that accepts
std::vector<std::unique_ptr<A>>& as a parameter

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

No. A std::vector<Foo> has no special relation to a std::vector<Bar> no matter what is the relation between Foo and Bar. They are two distinct completely different types. The fact that they are instantiations of the same class template is not relevant when you are asking for an exact type of argument of the function.

Thouh, the fact that they are instantiations of the same template enables you to employ duck typing. Make the function a function template. It can take either a std::vector<std::unique_ptr<T>> or simply a container of type C, or iterators of type Iter. As you know the base class B you know how the ducks walk and how the ducks quack and can implement the function template so it will work with either std::vector<std::unique_ptr<A>> or std::vector<std::unique_ptr<B>>.

("the ducks" is the classes inheriting from A and "how they walk and how they quack" is the interface of A)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading