I’m trying to implement a method where I pass along a base struct, which might be of type ‘derrived struct’.
However, when casting, I’m getting the following exception:
'To *TCastImpl<From,To,ECastType::UObjectToUObject>::DoCast(UObject *)': cannot convert argument 1 from 'From *' to 'UObject *'
To give you some basic information, here are my struct definitions:
Please be aware, these are just test structs, so the derrived struct doesn’t even have extra parameters, the message struct doesn’t even have message text.
FMessageStructBase:
#pragma once
#include "CoreMinimal.h"
#include "MessageStruct.generated.h"
USTRUCT()
struct FMessageStructBase
{
GENERATED_BODY()
public:
UPROPERTY()
int Id;
};
FMessageStructDerrived:
#pragma once
#include "CoreMinimal.h"
#include "MessageStruct.h"
#include "MessageStructDerrived.generated.h"
USTRUCT()
struct FMessageStructDerrived : public FMessageStructBase
{
GENERATED_BODY()
public:
};
The following code all contains the required include files for the structs in the cpp file:
#include "MessageStruct.h"
#include "MessageStructDerrived.h"
The code I use to test the casting is the following:
FMessageStructDerrived messageStruct;
FMessageStructBase* messageStructBase = &messageStruct;
FMessageStructDerrived* derrived = Cast<FMessageStructDerrived>(messageStructBase);
A “fix” I found, is to use static_cast instead, which compiles, and the cast succeeds. However, in the case of the message not being of the type FMessageStructDerrived, it will crash, since it’s not a safe cast:
FMessageStructDerrived* derrived = static_cast<FMessageStructDerrived*>(messageStructBase);
Luckily, I can of course use a dynamic_cast! … Oh. Wait. No I can’t, because if I use the following:
FMessageStructDerrived* derrived = dynamic_cast<FMessageStructDerrived*>(messageStructBase);
It will give me the following error:
'dynamic_cast': 'FMessageStructBase' is not a polymorphic type
I hope someone can help me figure out how I can properly cast these UStructs.
Thanks in advance!