Casting from QList<InheritedFromQObject> to QList<QObject>

  • Hi guys,
    I have a problem when casting:


    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?

  • Moderators

    You can't cast any container<A> to container<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 converting vector<int> to vector<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??

  • Moderators

    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* to string*. You can of course use reinterpret_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.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.