Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing a polymorphic vectors

I have an polymorphic problem.

void func(std::vector< BaseClass* > A){}

std::vector< SubClass* > B;

func(B); //Compile error C2664 

I get an error like so:

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

I also tried some weird stuff like have the parameter be a pointer to the vector and I pass the address of the vector like so:

void func(std::vector< BaseClass* > *A){}

std::vector< SubClass* > B;
func(&B); //same error  
like image 466
IE kills stay away from it Avatar asked Nov 30 '22 12:11

IE kills stay away from it


2 Answers

There is no such thing as a polymorphic vector. An std::vector, and every other container type in C++, including C style arrays always contains exactly one type. And the fact that two different containers have types that are related doesn't make the types of the containers related in any way.

In your case, you'll probably have to construct a second vector:

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

Note that trying to use an std::vector<DerivedClass*> as an std::vector<BaseClass*>, say by using a reinterpret_cast, is undefined behavior, and may not work. There's no guarantee that the actual phyical address of the BaseClass subobject in a DerivedClass object have the same pysical address as the complete object.

like image 194
James Kanze Avatar answered Dec 10 '22 12:12

James Kanze


Templates to the rescue:

template<typename T>
void func(std::vector<T> A)
{
    ...
}
like image 31
Some programmer dude Avatar answered Dec 10 '22 12:12

Some programmer dude