在c++ lambda表达式中调用类成员函数失败.处理步骤
Failed to call class member function in C++ lambda expression
//==== 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函数
您需要在[]
括号内提供this
捕获:
auto lambda2 = [this](string x1, string x2){cout << func2(x1,x2);};
如果没有它,编译器将不知道变量的上下文。注意,x1
和x2
都将被复制。
在这里阅读更多关于lambda捕获的信息
在Test::tst()
下的lambda
函数中,您有对func2
的调用。该调用不能完成,除非this
被lambda
函数捕获。
void tst(){
auto lambda2 = [this](string x1, string x2){cout << this->func2(x1,x2);};
}
相关文章:
- 为什么除非添加括号,否则构造函数上的模板替换会失败?
- 模板参数推导失败,函数参数/参数不匹配
- 从类型std::函数传递变量失败,尽管调用方期望的类型完全相同
- 如果我重新定义 sqrt 函数,为什么使用 std::sqrt 失败?
- C++ strcpy 函数在少数主要情况下失败
- 在构造函数中分配内存失败是如何冒泡的
- 无法调用成员函数,尝试正确执行此操作仍然失败
- 非静态成员失败的线程调用函数
- 使用用户定义的类型 UDT 实例化 std::atomic<>。如果 UDT 具有虚函数,则 l 墨水将失败。为什么?
- 使用显式模板参数列表和 [temp.arg.explicit]/3 的函数调用的演绎失败
- 函数返回时,带指针的复制构造函数失败
- WriteProcessMemory 在函数内部失败
- 从 C#-DLL 调用函数的 C++ 失败
- 使用已删除的函数进行编译失败,并显示 uclibc
- MPICH 的 MPI_Comm_dup() 在复制构造函数中失败
- 代码在 msvcrt .dll函数上设置断点失败
- 作为模板参数的成员函数指针在继承的成员函数上失败,如何以及为什么?
- 引用构造函数时链接失败
- 断言 sv_count !=0 失败 - 函数 train_auto,SVM 类型 - EPS_SVR
- C++失败函数的 while 语句