There is a std::variant class template in the standard library that is essentially a type-safe union. It is generally used when we are not sure in advance which object should be populated from our list of object types, so we assume that one of the specified objects must be there at a time.

Unreal Engine has an alternative implementation called TVariant that works the same, except that all the types in the declaring template parameter pack must be unique.

Code example

This is an example where either FString or int64 may be filled.

class AnyClass
{
	TVariant<FString, int64> StringOrInt64Holder;

public:
	void FillString(const FString& NewString)
	{
		StringOrInt64Holder.Set<FString>(NewString);
	}

	void FillInt64(int64 NewInt)
	{
		StringOrInt64Holder.Set<int64>(NewInt);
	}
};

Note that it is not supported by Unreal Engine’s reflection/property system and hence in Blueprints, garbage collection, save game files, etc.