實際上我有一個問題讓我大吃一驚,對某人來說是一個挑戰,你能幫我解決這個問題嗎?:
class UItemEntity : public UObject
{
GENERATE_BODY()
public:
template<typename T=FItemComponent>
T& GetComponent()
{
auto Result = Components[TYPE_ID(T)];
T Comp = reinterpret_cast<T>(Result);
return Comp;
}
private:
/** Map from Component's type ID to one of their instance associated to this entity. */
TMap<const char*, FItemComponent> Components;
}
(這是 Unreal c 代碼,但仍然是 c :P)
用法示例:
struct FTestComponent : public FItemComponent { }
UItemEntity* Item;
FTestComponent& Comp = Item->GetComponent<FTestComponent>();
我不知道如何轉換從地圖中檢索到的值……我嘗試了靜態、動態和重新解釋轉換,但沒有成功。
這是我遇到的錯誤型別:
ItemEntity.h: [C2440] 'reinterpret_cast': cannot convert from 'ValueType' to 'T'
這可能是一個架構問題,但我不知道如何解決:/我真的需要在這個 ItemEntity 上有一個 GetComponent。
謝謝 !
編輯 :
在@Frank 的幫助下,我終于成功了,需要考慮一些虛幻的東西。
這里是 :
class UItemEntity : public UObject
{
GENERATE_BODY()
public:
template<typename T=FItemComponent>
T& GetComponent()
{
const bool IsItemComponentType = std::is_base_of_v<FItemComponent, T>;
check(IsItemComponentType);
FItemComponent* ItemComp = *Components.Find(TYPE_ID(T));
return Cast<T>(ItemComp);
}
private:
/** Map from Component's type ID to one of their instance associated to this entity. */
TMap<const char*, FItemComponent*> Components;
}
uj5u.com熱心網友回復:
可能有一些我不知道的 Unreal 特定惡作劇在起作用,但在通用 C 代碼中,它看起來像這樣:
class UItemEntity : public UObject
{
GENERATE_BODY()
public:
template<typename T>
T& GetComponent()
{
static_assert(std::is_base_of_v<FItemComponent, T>);
return *static_cast<T*>(Components.at(TYPE_ID(T)).get());
}
private:
/** Map from Component's type ID to one of their instance associated to this entity. */
TMap<const char*, std::unique_ptr<FItemComponent>> Components;
}
解釋:
- 元素存盤為指標,因為可以在其中存盤不同的型別。
at()之所以使用,是因為如果條目丟失,該函式將無法回傳任何內容。static_cast<>讓編譯器知道從基礎到派生的轉換是有意的。- 指標被取消參考為一個參考
*。 static_assert()根據評論中的討論,我用 a 替換了默認模板引數。
你可能想使用std::shared_ptr,std::weak_ptr,std::reference_wrapper甚至是原始指標,而不是std::unique_ptr視情況而定。但是,如果沒有更多背景關系,很難判斷哪個是正確的,因此我在unique_ptr此示例中使用了基線。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/375305.html
上一篇:正確的可變引數包擴展
