如何在带有捕获的函数中传递lambda

How to pass a lambda in a function with a capture?

本文关键字:函数 lambda      更新时间:2023-10-16

我的标题是我的主要问题。下面的代码显示了我想要做的事情,但它导致了一个错误。

class B
{
public:
    void DoSomething(void (*func)())
    {
        func();
    }
};
class A
{
public:
    int x;
    void Start(B* b)
    {
        auto func = [this]()->void
        {
            this->x++;
        };
        b->DoSomething(func);
    }
};

如果我删除了"this"关键字,那么程序就可以工作了,但我不能引用x变量。

那么我该如何做到这一点呢?

更改

void DoSomething( void (*func)() )

void DoSomething( std::function<void()> func )

您当前的参数类型void (*func)()函数指针,这是一种不保持状态的可调用类型(可以像函数一样调用)。这就是为什么不能将变量this传递到函数中的原因。

只有不捕获任何内容的lambda才能转换为无状态函数指针

然而,std::function可以表示(几乎)任何可调用的东西。它可以是一个原始函数,或者是实现operator()的类的实例,也可以是您的lambda持有状态。

另一种选择是简单地使用模板来避免与需要由std::function打包的大型lambda相关的潜在开销。

#include <functional>
using namespace std;
template<typename Callable> 
void DoSomething(Callable c) { c(); }  // calls the lambda with no args
int main() 
{   
     DoSomething([]{ printf("Hellon"); });   
     DoSomething([msg = "World"] { printf("%sn", msg); });
}

Live代码:http://goo.gl/LMvm3a