TFunction as parameter syntax problem [SOLVED]

Hi all,
How does the syntax work for providing a function argument of the type TFunction given the following situation:

// in file 1
void UMyObject::StaticFunction(TFunction<void(AActor*)> functionAsParam)
{
   functionAsParam(GetSomeActor());
}

// in file 2
void AMyActor::FunctionUsingActor(AActor* UsedActor)
{ //...}

void AMyActor::OtherFunction()
{
  UMyObject::StaticFunction(// My FunctionUsingActor here);
}

I have tried:

UMyObject::StaticFunction(&FunctionUsingActor);
UMyObject::StaticFunction(&AMyActor::FunctionUsingActor);

But both do not work.
I get the error: cannot convert rvalue of type void(AMyActor::*)(AActor*) to parameter type TFunction<void(AActor*)

How do I provide a pointer to FunctionUsingActor so I can use it inside my StaticFunction?

Many thanks in advance.

This is due to the difference between a pointer to a static/free-function and a non-static function.

To call a method of a class using a function pointer, you also need an instance of that class. (C ++ usually implements this as a hidden parameter. AFAIK MSVC pass this in the RCX register, but it is an implementation detail.)

A pointer to a free/static function will always fit std::uintptr_t and can be safely stored as void*.
The pointer to the non-static class method is a different story. Such a function can be virtual, so instead of holding an address, it holds address to v-table and index of that function in v-table. In addition, inheritance can also be virtual, which complicates things even more.

To “bind” a class method to TFunction:

void AMyActor::FunctionUsingActor(AActor* UsedActor)
{
  UMyObject::StaticFunction( [this](AActor* Param) { FunctionUsingActor(Param); });
}

Note that you have to ensure that the class instance you are referring(this pointer) to in TFunction must exist at the time you call TFcuntion. Otherwise it will be a crash.

1 Like

Thank you for your elaborate response!! This solved my issue :slight_smile: