简体   繁体   中英

Cast QList of derived to QList of base

I have these classes:

class IParameter {};
class ModuleParameter : public IParameter {};

Now I have QList of derived:

QList<ModuleParameter*> list;

When I cast single item it's ok:

IParameter *p = list[0]; // ok

When I cast the list I've got an error.

QList<IParameter*> *list = static_cast<QList<IParameter*>*>(&list);

Invalid static_cast from type QList<ModuleParameter*>* to type QList<IParameter*>* .

So, how can I cast?

If you really want a QList<IParameter*>, you can do something like these:

    QList<A*> la;
    QList<B*> lb;
    ...
    std::transform(lb.cbegin(),
                   lb.cend(),
                   std::back_inserter(la),
                   [=](B* b)
    {
        return static_cast<A*>(b);
    });

QList is a template without common base class type and QList<ModuleParameter*> is a type unrelated to QList<IParameter*> , you can't access QList<ModuleParameter*> polymorphically through a pointer to QList<IParameter*> . What you trying to do is impossible to do this way.

Instead you may store pointers to ModuleParameter in QList<IParameter*> and use cast when accessing them.

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