如何通过捕获在函数中传递 lambda?
How to pass a lambda in a function with a capture?
我的标题是我的主要问题。
下面的代码显示了我想做什么,但它会导致错误。
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()
的 class 实例,也可以是您的 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("Hello\n"); });
DoSomething([msg = "World"] { printf("%s\n", msg); });
}
实时代码:http://goo.gl/LMvm3a
我的标题是我的主要问题。 下面的代码显示了我想做什么,但它会导致错误。
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()
的 class 实例,也可以是您的 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("Hello\n"); });
DoSomething([msg = "World"] { printf("%s\n", msg); });
}
实时代码:http://goo.gl/LMvm3a