C ++ Lambda-捕获成员变量 [英] C++ lambda - capture member variable
本文介绍了C ++ Lambda-捕获成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个具有指向内核函数的函数指针的类,该类可以从外部更改。
I have a class that has function pointer to kernel function, that can change from outside.
class Bar
{
public:
int i;
}
class Foo
{
public:
std::function<double()> kernel;
Bar bar;
};
int main()
{
Foo f;
f.kernel = []() -> double { return i * i; }; //this is not working obviously
}
如何实现行为例如呈现。读取lambda中的类变量。我可以通过在内部传递 f
并编写 f.bar.i
来绕过它,但这不是很好的解决方案。
How can I achieve behaviour that is "presented", eg. read class variables inside lambda. I can bypass it by passing f
inside and write f.bar.i
, but that is not very nice solution.
推荐答案
在C ++ 14中,您可以将其编写为:
In C++14 you can write it as,
f.kernel = [&i = f.bar.i]() -> double { return i * i; };
如果您没有C ++ 14,也可以创建另一个变量,
If you don't have C++14, you can alternatively create another variable,
int &i = f.bar.i;
f.kernel = [&i]() -> double { return i*i; };
尽管通过 f
并没有错编写 f.bar.i
。
Though there's nothing wrong with passing f
and writing f.bar.i
.
这篇关于C ++ Lambda-捕获成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文