在 node.js 中,我可以在 lambda 中编写 lambda 并捕获我想要的任何变量。但在 C++11 中,由于 lambda 函数实际上是仿函数对象,因此使用嵌套的 lambda 捕获变量并不那么容易。
我正在使用 [this]
来捕获这个指针,这样我就可以使用类成员了。但是在 lambda 内部,this
指针指向 lambda 而不是外部类。
void MyClass::myFunction() {
// call the lambda1
connect(action, trigger, [this]() {
// in the lambda1, call lambda2
sendCommand([this]() { // <-- I want `this` point to the outter class
this->myMember.log("something"); // myMember is the member of class MyClass
});
});
}
我知道可以通过将 this 重命名为另一个指针变量并捕获该变量而不是 this
来完成,但我认为这种方式很丑陋。
有没有更好的方法来捕获外部this
?
最佳答案
您只需捕获外部 lambda 的上下文:
#include <iostream>
struct Omg
{
int lol= 42;
Omg()
{
[this]{ [&]{ std::cout<< this-> lol; }(); }();
}
};
int main(){ Omg(); }
关于在另一个 lambda 中使用 lambda 捕获 C++11 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24388577/