【问题标题】:Failed to call class member function in C++ lambda expression在 C++ lambda 表达式中调用类成员函数失败
【发布时间】:2015-09-25 03:46:14
【问题描述】:
//==== 1 ====
string func1(string x1, string x2){
    return x1 + x2;
}
auto lambda1 = [](string x1, string x2){cout << func1(x1,x2);};

//==== 2 ====
class Test{
public:
    string func2(string x1, string x2){
        return x1 + x2;
    }
    void tst(){
        auto lambda2 = [](string x1, string x2){cout << func2(x1,x2);};
    }
};

lambda1 是对的。 但是 lambda2 出错了(在 g++ 4.8 下):

error: 'this' was not captured for this lambda function
         auto lambda2 = [](string x1, string x2){cout << func2(x1,x2);};

在 lambda 中调用成员函数的正确方法是什么?

【问题讨论】:

  • 错误提到捕获this。阅读 lambda 捕获是一个好的开始。
  • 请不要将答案放在问题中 - 将其发布为回答您的问题
  • 答案在下面的框中。您可以回答自己的问题。

标签: c++ lambda


【解决方案1】:

编译器会为您提供您正在寻找的答案:

错误:没有为这个 lambda 函数捕获“this”

您需要在[] 括号内提供this 捕获:

auto lambda2 = [this](string x1, string x2){cout << func2(x1,x2);};

没有它,编译器就不会知道变量的上下文。请注意,x1x2 都将被复制。

详细了解 lambda 捕获 here

【讨论】:

    【解决方案2】:

    Test::tst() 下的lambda 函数中,您可以调用func2。除非thislambda 函数捕获,否则该调用无法完成。

    void tst(){
        auto lambda2 = [this](string x1, string x2){cout << this->func2(x1,x2);};
    }
    

    应该这样做。

    【讨论】:

      猜你喜欢
      • 2021-01-07
      • 2020-05-28
      • 2019-11-29
      • 1970-01-01
      • 1970-01-01
      • 2011-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多