虚幻引擎支持向下转换 UObject*
通过 Cast<T>
并通过 custom implementation of dynamic_cast<T*>
.
下垂时 USTRUCT
对象,这两种方法都不起作用:
Cast<T>
的方法不支持转换为UScriptStructs
.- UE4 在没有 RTTI 的情况下编译(例如
/GR-
是为 cl.exe 设置的)并且 UE4 使用dynamic_cast<T*>
指向USTRUCT
的指针的实现秒。因此编译器抛出 C4541 (见下面的例子)。
UE4.22有没有安全downcast的方法USTRUCT
是否正在使用 UE4 的反射系统(所以当 static_cast<T*>
等不是一个选项时)?
如果不是,那为什么 UE4 不支持向下转型 USTRUCT
是通过它的 Cast 函数吗?例如。不应该引用它们还是与 Blueprint 相关的原因?
(2) 的示例,在 UE4 项目中使用:
#pragma once
#include "CoreMinimal.h"
USTRUCT()
struct MyStructBase
{
virtual ~MyStructBase() = default;
};
USTRUCT()
struct MyStructDerived : public MyStructBase
{};
void TestFunc()
{
auto lvalue = MyStructBase{};
auto lvaluePtr = &lvalue;
auto o = dynamic_cast<MyStructDerived*>(lvaluePtr); // cl.exe throws C4541
}
最佳答案
Is there a method in UE4.22 to safely downcast USTRUCTs using the reflection system of UE4 (so when static_cast<T*> etc is not an option)?
我知道这不是一个理想的解决方案,可能不适合你的情况,但如果你不想使用裸 static_cast
,你可以提供一个模板化函数来执行转换并添加一个包含 TIsDerivedFrom
的 static_assert
在转换失败时获取编译时错误。
template<typename T, typename U>
T* CastStruct(U* base)
{
static_assert(TIsDerivedFrom<T, U>::IsDerived, "Type T has to be derived from U.");
return static_cast<T*>(base);
}
why UE4 doesn't support downcasting
USTRUCTs
by its Cast functions?
那是因为结构在虚幻引擎中被认为是轻量级实体,因此反射——Cast
工作所必需的——未提供以最小形式提供他们。
使用指向 USTRUCTs
的指针时要小心,因为它们不仅不受反射支持,而且不受垃圾收集器、序列化器、UI 等的支持。在处理它们时你必须知道你在做什么.
关于c++ - 如何安全地向下转换 USTRUCT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56090903/