Is there a way to verify a struct's type before using it?

I have a list of structs set up like this:


USTRUCT()
struct FBaseStruct{
	GENERATED_USTRUCT_BODY()
		float baseFloat;
		int32 baseInt;
		EStructType myType;
};


USTRUCT()
struct FSubtructA : public FBaseStruct {
	GENERATED_USTRUCT_BODY()
		TMap<int32, FString> differentUniqueValues;
};

USTRUCT()
struct FSubtructB : public FBaseStruct {
	GENERATED_USTRUCT_BODY()
		TArray<FString> uniqueValues;
};

I have a giant TArray that I want to divide up by subclass, which is easy enough:



TArray<FBaseStruct> baseArray;

for (int i = 0; i < baseArray.Nunm(); i++){

	switch (EStructType){
		case EStructType::StructA:
			//do stuff with tmaps
			break;
		case EStructType::StructB:
			//do stuff with strings
			break;
		default:
			break;
	}
}

Here’s where I’m stuck; how do I verify which subclass of EBaseStruct each array entry is? If the enum somehow gets set wrong, and I pass my system a SubstructA that thinks it’s a SubstructB, I’m going to end up referencing a bunch of values that don’t exist, confusing myself at best and crashing at worst.

So is there some kind of safety/sanity feature I can add, which verifies my substruct’s class before referencing it?

Nope, C++ does not maintain type information at runtime. (Actually, it can do if RTTI is enabled, in which case you can use dynamic_cast. But enabling it is rare, especially for performance critical programs. I’m pretty sure it’s not enabled for UE4 projects, especially since UE4 has it’s own runtime type system in the form of UClass.)

More to the point, you can’t even use


TArray<FBaseStruct>

in that way. It would need to be


TArray<FBaseStruct*>

or an equivalent using smart pointers.

You could restrict through encapsulation and constructors how myType gets set, so that it is automatically assigned the right value based on what kind of argument is passed into a constructor, and cannot be altered. That should be plenty enough to ensure you don’t get inconsistent states arising.

An alternative, probably better, is to look at using a variant container. UE4 has its own, TUnion, though at first glance it looks like it’s limited to a maximum of 6 possible types.