Download

Pass "this" as reference in delegate

Here is a snippet of code (which doesn’t compile). I’m trying to figure out how to make this work and compile. I’ve stripped out all the unnecessary stuff just to show the problem.



struct FMyStruct;

DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FChanged, FMyStruct&, MeRef, int32, Index);


USTRUCT(BlueprintType)
struct FMyStruct
{
	GENERATED_USTRUCT_BODY()

	FChanged OnChanged;
};


So I want to have a delegate that an instance of FMyStruct can broadcast and pass a reference to itself. The problem is that FMyStruct needs to know about the delegate definition, while the delegate needs to know about the struct definition. So this creates a “chicken or the egg” problem. I thought I could simply forward declare the struct like shown in the snippet above, but that fails. When trying to compile I get this error, “Unrecognized type ‘FMyStruct’ - type must be a UCLASS, USTRUCT or UENUM”

Help! :frowning:

Can’t you put the struct definition before the DECLARE_DYNAMIC_MULTICAST macro?

That one should compile, no?

Unfortunately not. The struct also needs to know about the delegate.

From what I can seem, this is a limitation of UHT - it can deal with a pointer to a forward declared UCLASS in this situation, but not a reference to a forward declared USTRUCT. Now I think about it, I have a feeling that the generated code for passing a USTRUCT by reference actually needs the struct to be fully defined, so this is probably why.

You’ll have to work around this, perhaps by somehow storing the delegate on the UCLASS in which the USTRUCT is embedded.

Strictly speaking, there is very little difference between a Struct and a Class in C++. UE4 further enforces these into struct=reference,class=pointer roles which cause issues like these.

Best bet in this case is to simply convert your USTRUCT to a UCLASS and then use forward declaration as normal. It’s not the best solution, but it’s the simplest.