Download

How to make a Delegate function parameter as optional

I’m would like to pass a Delegate as a parameter to a function. It works fine, but now I would like to make the Delegate parameter as optional.

Currently I have this:



void MyFunction(FMyDelegate pDelegateParam);


And I would like to make something like this:



void MyFunction(FMyDelegate pDelegateParam = Something);


Not sure if it’s even possible though… Any suggestions?

EDIT: I forgot to mention, I aim to use the function on Blueprint. If I use the version without the optional parameter when I use that function node it forces me to put a pin for the delegate.

For now I found a workaround: I create a struct as a wrapper, which contains only the delegate. Like this:



USTRUCT(BlueprintType)
struct FDelegateStruct
{
    GENERATED_USTRUCT_BODY()

    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="MyDelegates")
    FMyDelegate delegate;

    FDelegateStruct()
    {

    }
};


And the function signature becomes:



void MyFunction(FDelegateStruct pDelegateStruct);


This way in Blueprint I’m not forced to put a pin in it. Still, in C++ it’s a forced parameter, but I can pass an empty struct.

I actually have more than one delegate in my situation, and I put them all in the struct. The problem with multiple delegates in the struct is that in Blueprint when I do want to pass a delegate as parameter
I have to create the struct and if I do I’m forced to assign ALL delegates (even those I don’t care about), like this:

Still, it’s a better solution than before. To fix this I could create a wrapper struct for EVERY delegate, but I don’t like this solution very much.

If anyone has a better solution, please share! :slight_smile:

To make optional a delegate param in BP you need to add AutoCreateRefTerm meta to UFUCNTION macro like this:


UFUNCTION (BlueprintCallable, Category = "Foo", meta = (AutoCreateRefTerm = "FooCallback"))
void Foo (const FMyDelegate& FooCallback);

In the other hand, to works in CPP you must create empty delegate like this:



void SomeFunction ()
{
   Foo (FMyDelegate ());
}

I don’t found how to make optional a delagate in code :frowning: