gpt4 book ai didi

c++ - Lambda`s internal this in c++

转载 作者:太空宇宙 更新时间:2023-11-03 10:39:09 25 4
gpt4 key购买 nike

如果 lambda 函数 ic C++ 是由仿函数实现的,为什么这是不可能的?

#include <iostream>

class A
{
public:
int a;
void f1(){ [](){std::cout << this << std::endl ;}();};
};

int main()
{
A a;
a.f1();
}

我收到错误 9:34: error: 'this' was not captured for this lambda function。如果我理解正确,如果 lambda 是作为仿函数类实现的,为什么无法获取它的内部 this

编辑:仿函数类的this,而不是A类实例的this

最佳答案

来自 lambda :

For the purpose of name lookup, determining the type and value of the this pointer and for accessing non-static class members, the body of the closure type's function call operator is considered in the context of the lambda-expression.

struct X {
int x, y;
int operator()(int);
void f()
{
// the context of the following lambda is the member function X::f
[=]()->int
{
return operator()(this->x + y); // X::operator()(this->x + (*this).y)
// this has type X*
};
}
};

所以,不可能如你所愿地引用this

关于c++ - Lambda`s internal this in c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48627472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com