简体   繁体   中英

How to add a base class to a vector of derived classes

I have a std::vector that holds shared pointers to a derived class cDerivedClass , I also have shared pointers for the base class too. So something like this:

typedef SHARED_PTR<cBaseClass> cBaseClassPtr;

typedef SHARED_PTR<cDerivedClass> cDerivedClassPtr;

std::vector<cDerivedClassPtr> vDerivedPtrList;

Now if I want to have a CDerivedClass::AddComponent(cBaseClassPtr inpBaseClass) method that takes an argument of type cBaseClassPtr and adds it to the vector (vDerivedPtrList) of derived classes, how would I go about doing this?

I know dynamic_cast won't work since base-to-derived conversions are not allowed with dynamic casts unless the base class is polymorphic. I've tried static casting the cBaseClassPtr to a cDerivedClassPtr, but I'm thrown an error.

void cDerivedClass::AddComponent(cBaseClassPtr inpBaseClass)
{
    MY_ASSERT(inpBaseClass, "Component cannot be NULL");

    cDerivedClassPtr pDerviedPtrToAdd = static_cast<cDerivedClassPtr>(inpBaseClass);

    this->mvComponentList.push_back(pDerviedPtrToAdd);
}

Edit: To be exact this is the error I'm getting:

No matching conversion of static_cast from 'cBaseClassPtr' (aka 'shared_ptr<cBaseClassPtr>') to 'cDerivedClassPtr' (aka 'shared_ptr<cDerivedClassPtr>');

I'm using boost's implementation of smart pointers boost::shared_ptr

If your CDerivedClass::AddComponent function can only really deal with cDerivedClassPtr s, then adjust its signature accordingly :

CDerivedClass::AddComponent(cDerivedClassPtr inpDerivedClass)

If it should be able to deal with cBaseClassPtr , then adjust the definition of vDerivedPtrList to hold cBaseClassPtr s :

std::vector<cBaseClassPtr> vBasePtrList;

It is difficult to know exactly what you are trying to do here, and what smart-pointer implementation you are using.

Why is your base class not polymorphic? If it were you could use some kind of double-dispatch to get it to add itself to an appropriate collection.

If there is a different vector for each derivation, then each derived class would know which one it is supposed to add itself to.

You will need your base class to derive from enable_shared_From_this so it can shared-pointer itself if it is already currently shared_ptred (which presumably it is): although that will shared_ptr itself into the base type you can then create another shared_ptr based on the life of the first and put that in the collection.

(That is assuming you are using boost and I think std has the same interface)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM