How to pass variables to method references?

Hi guys, I am a UE4 and C++ beginner coming from the Java world. As of version 8, Java supports lambda expressions and method references. There are code parts in C++ which look pretty similar.

// Java:
world.getTimerManager().setTimer(timerHandle, this::foo, 1.0f);
// C++:
World->GetTimerManager().SetTimer(TimerHandle, this, &AMyClass::Foo, 1.0f);  

I guess &AMyClass::Foo is a reference (pointer) to the method Foo of the class AMyClass, which is being run for this by the implementation of the SetTimer(...) method. Am I right?

Therefore, I assume that we have a different technical approach than in Java, since Java lambda expressions are based on implementations of functional interfaces. In Java, we have object instances and therefore known method signatures, in C++, we have a pointer to a method, but the method signature, or at least the parameter list, is unknown, right?

Is it still possible to somehow pass a variable to &AMyClass::Foo as a method parameter?

// Java:
world.getTimerManager().setTimer(timerHandle, () -> foo(param), 1.0f);
// C++:
World->GetTimerManager().SetTimer(TimerHandle, ..., ..., 1.0f);

You cannot do this with member function pointers. The required signature for the member function pointer is fixed in the definition of SetTimer.

It is also impossible in C++ to use lambdas as member function pointers, because lambdas are not bound to an object.

You can however use another overload of SetTimer:

void SetTimer(FTimerHandle& InOutHandle, TFunction<void(void)>&& Callback, float InRate, bool InbLoop, float InFirstDelay = -1.f );

Which allows you to use a lambda function like this:

World->GetTimerManager().SetTimer(TimerHandle, [param](){foo(param);}, 1.f);

Where the [param] part is called capture, that allows you to capture any variables from the outer scope into the lambda function either by copy (which is the default) or by reference using [&param].

Of course you can also capture this which allows you to call a member function with param in the lambda:

World->GetTimerManager().SetTimer(TimerHandle, [this, param](){this->foo(param);}, 1.f);
// which is then similar to your java example
world.getTimerManager().setTimer(timerHandle, () -> foo(param), 1.0f);

See here for complete documentation of C++ lambda functions: http://en.cppreference.com/w/cpp/language/lambda

Hi, thanks for your help. I’ll give it a try.

Works as expected, many thanks!