Passing polymorphic vectors

I have a polymorphic problem.

void func(std::vector< BaseClass* > A){} std::vector< SubClass* > B; func(B); //Compile error C2664 

I get this error:

  error C2664 'func' : cannot convert parameter from 'std::vector<_Ty>' to 'std::vector<_Ty>' with [ _Ty=B * ] and [ _Ty=A * ] 

I also tried some strange things, for example, so that the parameter is a pointer to a vector, and I pass the address of the vector like this:

 void func(std::vector< BaseClass* > *A){} std::vector< SubClass* > B; func(&B); //same error 
+4
source share
3 answers

There is no such thing as a polymorphic vector. std::vector and any other type of container in C ++, including C type arrays always contain exactly one type. And the fact that two different containers have types that are connected does not make the types of containers connected in any way.

In your case, you probably have to build a second vector:

 func( std::vector< BaseClass* >( B.begin(), B.end() ) ); 

Note that trying to use std::vector<DerivedClass*> as std::vector<BaseClass*> , say with reinterpret_cast , is undefined and may not work. There is no guarantee that the actual physical address of the BaseClass subobject in a DerivedClass object has the same physical address as the full object.

+10
source

Rescue Templates:

 template<typename T> void func(std::vector<T> A) { ... } 
+6
source

The fact that this is-a that does not mean that the collection from this is that .

See what can happen if you are allowed what you wanted:

 void func(std::vector<BaseClass*>& A) { A.push_back(new BaseClass); } std::vector<SubClass*> B; func(B); 

Oops! B now contains something that is not a pointer to a SubClass , and the program that shares it is undefined.

You need to make a copy with the correct type, use templates or refactoring so that you do not need to transfer the collection.

+5
source

Source: https://habr.com/ru/post/1487852/


All Articles