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?
CodePudding user response:
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);
});
CodePudding user response:
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.
