Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphism, why can't I do this?

class BaseA
{
}

class B : public BaseA
{
}

template <class T>
class C : public vector<T>
{
}

void someFunction (void)
{
    C<B> myClass;

    // I can't seem to do this...is it not possible?
    vector<BaseA> converted = ((vector<BaseA>) myClass);
}

See comment in code for what I am trying to do.

like image 869
Cheetah Avatar asked Dec 07 '22 15:12

Cheetah


2 Answers

A vector of B isn't a vector of A even if B is an A (I assume a mixup between A and BaseA)

Try

vector<A> converted(myClass.begin(), myClass.end());

which is probably what you want to express.

(BTW inheriting from vector is bad idea in general, it isn't designed for that.)

like image 147
AProgrammer Avatar answered Dec 21 '22 04:12

AProgrammer


C<B> and vector<A> are completely unrelated types and you would have to explicitly define such a conversion (e.g. template <typename TargetValueType> explicit operator vector<TargetValueType> () { ... }).

If such conversion is an uncommon task, something that is not really natural to the nature of your class, it might be preferable to use a range constructor (see AProgrammer's answer).

Also: If vector is std::vector, deriving from it is not a good idea. It isn't defined as a base class, and typically you should prefer containment over derivation (as it imposes looser coupling on your clients).

like image 44
Sebastian Mach Avatar answered Dec 21 '22 03:12

Sebastian Mach