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

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

最佳答案

编译器给你你正在寻找的答案:

error: 'this' was not captured for this lambda function

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

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

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

阅读更多关于 lambda 捕获的信息 here .

关于c++ - 无法在 C++ lambda 表达式中调用类成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32774451/

相关文章:

C++,静态对象的构造函数中的异常绕过先前静态对象的析构函数

c++ - 在 .NET 中捕获非托管 dll 异常

c# - 在通用参数中使用多态性

java - 带参数的可调用 lambda 表达式

c# - 使用 Rhino.Mocks 检查传递给委托(delegate)的预期值

c++ - 按值捕获 shared_ptr 的 lambda 如何影响它的 use_count()?

c++ - Arduino 上的结构 : function() 'does not name a type'

c++ - 在通过 native 字符串创建 BSTR(使用 _bstr_t 包装器)时,如何设置长度?

c++ - 在没有管理员权限的情况下安装 Qt

python - Pandas 分配 Lambda 函数