如何在捕获函数中传递lambda?

Ass*_*ast 9 c++ lambda

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

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);
    }
};
Run Code Online (Sandbox Code Playgroud)

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

那我该怎么做呢?

Dre*_*ann 7

更改

void DoSomething( void (*func)() )
Run Code Online (Sandbox Code Playgroud)

void DoSomething( std::function<void()> func )
Run Code Online (Sandbox Code Playgroud)

当前参数void (*func)()是一个函数指针,它不保持状态.这就是为什么你的变量this不能传递给函数的原因.只捕获任何内容的lambda都可以转换为无状态函数指针.

std::function但是可以表示任何可调用的,不带参数并且不返回任何内容.它可以是原始函数,operator()也可以是实现类的实例,也可以是lambda保持状态.


rpa*_*lin 5

另一种方法是简单地使用模板来避免与需要由 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("Hello\n"); });   
     DoSomething([msg = "World"] { printf("%s\n", msg); });
}
Run Code Online (Sandbox Code Playgroud)

实时代码:http : //goo.gl/LMvm3a