简体   繁体   English

Lambda 用于 class 的 function 指针

[英]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.我正在使用信号/插槽库( https://github.com/pbhogan/Signals )并且我希望该方法能够具有不同的签名作为事件。 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.现在我正在使用没有参数的 Signal 来测试拦截呼叫。

The Connect() method takes 2 parameters. Connect() 方法采用 2 个参数。 The object pointer and the object classes function pointer. object 指针和 object 类 function 指针。 Is there any way I can make a lambda to intercept this call?有什么办法可以让 lambda 拦截这个电话?

这里的签名

I tried doing the below but it's giving syntax error.我尝试执行以下操作,但它给出了语法错误。

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

error:错误:

在此处输入图像描述

It's been about 10 years since I worked in C++ and mostly work in C# so not sure if this is possible.自从我在 C++ 工作以来已经大约 10 年了,并且主要在 C# 工作,所以不确定这是否可能。 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.由于它是我正在使用的现有库,因此我正在尝试使其适合我可以获得调用回调的 lambda 这将允许我调用 soundComponents PlaySound() 方法,该方法可能具有不同的参数结构,我可以 map调用 playerComponent 的 OnJump 参数。 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.这允许组件由未在参数结构上进行通信的不同程序员开发,并为所述组件的用户提供灵活性来决定如何处理 arguments。

I'm using Visual Studio 2019 so thinking it's the most modern version of C++.我正在使用 Visual Studio 2019,所以认为它是 C++ 的最现代版本。

One nice property of lambdas is that they're objects - they generate an anonymous class with the call operator overloaded. lambda 的一个很好的特性是它们是对象——它们生成一个匿名的 class 调用运算符重载。 And a nice property of operator overloads in C++ is that they can be treated like methods. C++ 中运算符重载的一个很好的特性是它们可以被视为方法。

The Signal0 class expects a pointer to an object, and a pointer-to-member to a method in that object's class. Signal0 class 需要一个指向 object 的指针,以及指向该对象 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:因此,要连接 lambda,您可以将 lambda 本身用于 object,并使用指向其调用运算符的指针作为方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM