Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphic QSharedPointer

I'm trying to use QSharedPointer in my polymorphic stucture, but I couldn't find right syntax to convert pointer of base class to pointer of derived class.

struct Switch : State {
 int a;
};

QSharedPointer <State> myState=QSharedPointer <State>(new Switch);  

QSharedPointer <Switch> mySwitchTest= ??? myState;

What should I put in the place of ???

like image 748
metdos Avatar asked Aug 17 '10 07:08

metdos


2 Answers

Use qSharedPointerCast():

QSharedPointer <Switch> mySwitchTest= qSharedPointerCast<Switch>(myState);

Or call staticCast() on the smart pointer:

QSharedPointer <Switch> mySwitchTest= myState.staticCast<Switch>();

Both versions are basically equivalent to doing static_cast on raw pointers.

like image 140
In silico Avatar answered Sep 21 '22 17:09

In silico


For a dynamic cast, use qSharedPointerDynamicCast:

class Derived : public Base { ... };
QSharedPointer<Base> base...

QSharedPointer<Derived> derived = qSharedPointerDynamicCast<Derived>( base );

There are also equivalents for static_cast (as in silico showed), qobject_cast and const_cast. Pick your poison.

like image 25
Frank Osterfeld Avatar answered Sep 21 '22 17:09

Frank Osterfeld