无法在C ++ lambda表达式中调用类成员函数

时间:2015-09-25 03:46:14

标签: c++ lambda

//==== 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中调用成员函数的正确方法是什么?

2 个答案:

答案 0 :(得分:1)

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

  

错误:&#39;这个&#39;没有为这个lambda函数捕获

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

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

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

阅读有关lambda捕获here的更多信息。

答案 1 :(得分:0)

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

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

应该这样做。