title: How to safely downcast USTRUCTs
body: <p>Unreal Engine supports downcasting of <a href="https://api.unrealengine.com/INT/API/Runtime/CoreUObject/UObject/UClass/" rel="nofollow noreferrer"><code>UObject*</code></a> via <a href="https://api.unrealengine.com/INT/API/Runtime/CoreUObject/Templates/" rel="nofollow noreferrer"><code>Cast&lt;T&gt;</code></a> and via a <a href="https://api.unrealengine.com/INT/API/Runtime/CoreUObject/Templates/UE4Casts_Private__DynamicCast/" rel="nofollow noreferrer">custom implementation of <code>dynamic_cast&lt;T*&gt;</code></a>.</p>
  
  <p>When downcasting <a href="https://api.unrealengine.com/INT/API/Runtime/CoreUObject/UObject/UScriptStruct" rel="nofollow noreferrer"><code>USTRUCT</code></a> objects, both methods don't work:</p>
  
  <ol>
  <li>The methods of <code>Cast&lt;T&gt;</code> do not support conversions to <code>UScriptStructs</code>.</li>
  <li>UE4 compiles without RTTI (e.g. <a href="https://docs.microsoft.com/en-us/cpp/build/reference/gr-enable-run-time-type-information?view=vs-2019" rel="nofollow noreferrer"><code>/GR-</code></a> is set for cl.exe) and UE4 uses the <code>dynamic_cast&lt;T*&gt;</code> of the implementation for pointers to <code>USTRUCT</code>s. Therefore the compiler throws <a href="https://docs.microsoft.com/en-us/cpp/error-messages/compiler-warnings/compiler-warning-level-1-c4541" rel="nofollow noreferrer">C4541</a> (see example below).</li>
  </ol>
  
  <p>Is there a method in UE4.22 to <em>safely</em> downcast <code>USTRUCT</code>s using the reflection system of UE4 (so when <code>static_cast&lt;T*&gt;</code> etc is not an option)?</p>
  
  <p>If not, then why UE4 doesn't support downcasting <code>USTRUCT</code>s by its Cast functions? E.g. shouldn't they be referenced or are the reasons Blueprint related?</p>
  
  <hr>
  
  <p>Example for (2), use within an UE4 project:</p>
  
  <pre><code>#pragma once
  #include "CoreMinimal.h"
  
  USTRUCT()
  struct MyStructBase
  {
      virtual ~MyStructBase() = default;
  };
  
  USTRUCT()
  struct MyStructDerived : public MyStructBase
  {};
  
  void TestFunc()
  {
      auto lvalue = MyStructBase{};
      auto lvaluePtr = &amp;lvalue;
      auto o = dynamic_cast&lt;MyStructDerived*&gt;(lvaluePtr); // cl.exe throws C4541
  }
  </code></pre>