简体   繁体   English

如何在lambda中捕获此对象的变量?

[英]How to capture a variable of this object in lambda?

I have seen many answers on SO asking about capturing this by reference but I have a different question. 我已经看到很多关于SO的答案,要求通过引用来捕获this ,但我有一个不同的问题。 What if I want to capture a specific variable owned by this object? 如果我想捕获this对象拥有的特定变量, this怎么办?

For example: 例如:

auto rel_pose = [this->_last_pose["main_pose"],&pose](Eigen::VectorXd pose1, Eigen::VectorXd pose2)
    {
        // Some code
        return pose;
    };

I want to capture the specific variable of this by value and use it inside my lambda expression. 我想捕捉的具体变量this按价值计算,使用它我的lambda表达式内。 Why this is not possible? 为什么这不可能?

It's possible: 这是可能的:

struct S
{
    int i = 7;
    char c = 0;
};

int main(int argc, char* argv[])
{
    S s;
    auto l = [integer = s.i]() {
        return integer;
    };

    return l();
}

You can apply by-copy capture with an initializer (since C++14) (or by-reference capture with an initializer, depends on your demand), eg 您可以使用初始化程序 (因为C ++ 14)(或使用初始化程序的引用捕获,取决于您的需求)应用副本捕获 ,例如

auto rel_pose = [some_pose = this->_last_pose["main_pose"], &pose](Eigen::VectorXd pose1, Eigen::VectorXd pose2)
{
    // Some code using some_pose
    return pose;
};

Note that we can only capture identifiers in lambda, we can't capture expressions like this->_last_pose["main_pose"] directly. 请注意,我们只能捕获 lambda中的标识符,我们无法直接捕获这样的表达式this->_last_pose["main_pose"] The captures with an initializer just solve such issues straightforward. 使用初始化程序捕获只是简单地解决了这些问题。

Why this is not possible? 为什么这不可能?

It's possible, like other answers show. 有可能,就像其他答案所示。 But you must do it explicitly . 但你必须明确地做到这一点 Accessing any member of the current object in the lambda is transformed automatically to an access through the this pointer. 访问lambda中当前对象的任何成员将通过this指针自动转换为访问。 When you write a plain [this->_last_pose["main_pose"],&pose] , what's really captured is this , and the access to _last_pose goes through it. 当你写一个普通的[this->_last_pose["main_pose"],&pose] ,真正捕获的是this ,并且对_last_pose的访问_last_pose通过它。

It's simply how lambda captures are specified for member variables. 它只是为成员变量指定lambda捕获的方式。 Be grateful you are compiling C++14. 不胜感激,你正在编译C ++ 14。 In C++11 capturing members by value was not as easy as adding an init capture that does an copy. 在C ++ 11中,按值捕获成员并不像添加执行副本的init捕获那么容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM