Home > Enterprise >  Consider Vector of Child Pointers as Vector of Base Pointers
Consider Vector of Child Pointers as Vector of Base Pointers

Time:10-31

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

CodePudding user response:

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)

  • Related