4

i have to change my code from using std::shared_ptr<Type> to TSharedPtr<Type> (so i can use unreal engine's delegates properly), but there is a problem - i can't find function to replace std::dynamic_pointer_cast<To>(std::shared_ptr<From>), there is only a StaticCastSharedPtr<To>(TSharedPtr<From>), but i need to be able to check if the object is of derived type in runtime, static casting won't help with that, am i missing something?

Notrum666
  • 303
  • 1
  • 10
  • You can always try to emulate it as `dynamic_cast(from.get()) ? StaticCastSharedPtr(from) : TSharedPtr()` – Artyer Oct 24 '22 at 16:49

1 Answers1

1

The way to do dynamic casting in Unreal Engine is just to simply call the Cast function. In case you're curious, that function returns TCastImpl<From, To>::DoCast(Src), and the DoCast function is implemented as follows as of UE 5.0,

// This is the cast flags implementation
FORCEINLINE static To* DoCast( UObject* Src )
{
    return Src && Src->GetClass()->HasAnyCastFlag(TCastFlags<To>::Value) ? (To*)Src : nullptr;
}

In UE 4.25 and below, before using cast flags, DoCast would call IsA instead to determine whether a pointer could be safely casted. Now it just uses bitwise operations between the source and destination object types' cast flags to see if the cast can be done.

Quick example: Assuming I had a custom AActor class called AWizard and a variable of type AActor* called SomeActor, may or may not be a wizard actor.

if (AWizard* Wizard= Cast<AWizard>(SomeActor)) {
    // Cast succeeded
}
else {
    // Cast returned nullptr
}
Chris Gong
  • 8,031
  • 4
  • 30
  • 51