簡體   English   中英

在另一個lambda中包含lambda的C ++ 11變量捕獲

[英]C++11 variable capture with lambda inside another lambda

在node.js中,我可以在lambda中編寫lambda並捕獲我想要的任何變量。 但是在C ++ 11中,由於lambda函數實際上是函子對象,因此使用嵌套lambda捕獲變量並不那么容易。

我正在使用[this]捕獲此指針,因此可以使用類成員。 但是在lambda中, this指針指向lambda而不是outter類。

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嗎?

但是在lambda中, this指針指向lambda而不是outter類。

不,在lambda內部, this與外部具有相同的值。 在你的代碼的唯一問題是訪問this. 代替-> 該程序:

void MyClass::myFunction() {
    std::cout << this << std::endl;
    // call the lambda1
    connect(action, trigger, [this]() {
        std::cout << this << std::endl;
        // in the lambda1, call lambda2
        sendCommand([this]() {      // <-- I want `this` point to the outter class
            std::cout << this << std::endl;
            this->myMember.log("something");  // myMember is the member of class MyClass
        });
    });
}

在所有三個位置為此打印相同的值

g++ -std=c++11 -O3 -Wall -Wextra -pedantic -pthread main.cpp && ./a.out
0x7fff4286c80f
0x7fff4286c80f
0x7fff4286c80f

N3936(C ++ 14工作草案)[expr.prim.lambda] / 18指出:

lambda 表達式復合語句中的每個id表達式 (通過副本捕獲的實體的odr用法(3.2))都轉換為對閉包類型的相應未命名數據成員的訪問。 [ 注意:不是odr-use的id表達式是指原始實體,而不是閉包類型的成員。 此外,這種id表達式不會導致隱式捕獲實體。 - 注完 ]如果this被捕獲,每個ODR使用的this被轉換成到閉合型,流延(5.4)到的類型的相應的未命名數據成員的訪問this [ 注意:強制類型轉換確保轉換后的表達式是prvalue。 尾注 ]

您只需捕獲外部lambda的上下文:

#include <iostream>

struct Omg
{
  int lol= 42;

  Omg()
  {
    [this]{ [&]{ std::cout<< this-> lol; }(); }();
  }
};

int main(){ Omg(); }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM