user441521
user441521

Reputation: 6998

Lambda for function pointer of class

I'm using a signal/slot library (https://github.com/pbhogan/Signals) and I want the method to be able to have a different signature as the event. So I figure I'll need to intercept the call and make my own call so I can do any kind of argument manipulation. Right now I'm using a Signal with no parameters just to test intercepting the call.

The Connect() method takes 2 parameters. The object pointer and the object classes function pointer. Is there any way I can make a lambda to intercept this call?

The signature here

I tried doing the below but it's giving syntax error.

    playerComponent->OnJump.Connect(&*soundComponent, std::function<void()>([&]() -> void {
    soundComponent->PlaySound();
    }));

error:

enter image description here

It's been about 10 years since I worked in C++ and mostly work in C# so not sure if this is possible. Since it's an existing library I'm using I'm trying to make it fit where I can get a lambda called for the callback which would allow me to call the soundComponents PlaySound() method which could have a different parameter structure that I can map the calling playerComponent OnJump parameter to. This allows components to be developed by different programmers that didn't communicate on argument structure and gives flexibility to the user of said components to decide what to do with the arguments.

I'm using Visual Studio 2019 so thinking it's the most modern version of C++.

Upvotes: 2

Views: 213

Answers (1)

parktomatomi
parktomatomi

Reputation: 4079

One nice property of lambdas is that they're objects - they generate an anonymous class with the call operator overloaded. And a nice property of operator overloads in C++ is that they can be treated like methods.

The Signal0 class expects a pointer to an object, and a pointer-to-member to a method in that object's class. So to connect a lambda, you can use the lambda itself for the object, and a pointer to its call operator as the method:

auto proxy = [&]() -> void { soundComponent->PlaySound(); };
playerComponent->OnJump.Connect( &proxy, &decltype(proxy)::operator () );

Upvotes: 1

Related Questions