Casting from QList<InheritedFromQObject> to QList<QObject>
-
Hi guys,
I have a problem when casting:/home/kofr/dev/shit/Converter/converter.cpp:98:
error: invalid static_cast from type 'QList<Unit*>*' to type 'QList<QObject*>* '
sourceUnitDataModel = static_cast<QList<QObject *> *>((&modelsByCategory[category]));
Class Unit is the inherited from QObject class. What might be a problem?
-
You can't cast any
container<A>
tocontainer<B>
. Template class types are unrelated, even if T in them has something in common. There might be specializations, some sizes may differ, alignment may vary or buncha other things. Yours is just a special case but these types are just not compatible in general. For compiler it's basically the same as convertingvector<int>
tovector<string>
.The correct way to do what you want is to create another container and copy the elements casting them one at a time, e.g. using std::transform.
-
You can't cast any
container<A>
tocontainer<B>
. Template class types are unrelated, even if T in them has something in common. There might be specializations, some sizes may differ, alignment may vary or buncha other things. Yours is just a special case but these types are just not compatible in general. For compiler it's basically the same as convertingvector<int>
tovector<string>
.The correct way to do what you want is to create another container and copy the elements casting them one at a time, e.g. using std::transform.
@Chris-Kawa thx.
I actually cast pointers to containers. does this fact make any difference?? -
@Chris-Kawa thx.
I actually cast pointers to containers. does this fact make any difference??The two list types are unrelated so casting pointers to them is still not ok at all. To push the previous analogy - for compiler it's like casting
int*
tostring*
. You can of course usereinterpret_cast
and the compiler will be happy to trust you, but that is in no way correct and will obviously explode in your face at runtime.