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
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.
Templates to the rescue:
template<typename T>
void func(std::vector<T> A)
{
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With