我的标题是我的主要问题。 下面的代码显示了我想要做的事情,但它会导致错误。
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);
}
};
如果我删除"这个"关键字,然后程序工作,但后来我不能引用x变量。
那我怎么能实现这个目标呢?
答案 0 :(得分:7)
更改
void DoSomething( void (*func)() )
到
void DoSomething( std::function<void()> func )
当前参数void (*func)()
是函数指针,它不保持状态。这就是为什么你的变量this
无法传递给函数的原因。只捕获任何内容的lambda都可以转换为无状态函数指针。
std::function
可以表示任何可调用的,它不带任何参数并且不返回任何内容。它可以是原始函数,也可以是实现operator()
的类的实例,或者它可能是您的lambda保持状态。
答案 1 :(得分:4)
另一种方法是简单地使用模板来避免与需要由std :: function打包的大型lambdas相关的潜在开销。
#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